简体   繁体   English

C ++中来自string / int的字节

[英]Byte from string/int in C++

I'm a beginning user in C++ and I want to know how to do this: How can I 'create' a byte from a string/int. 我是C ++的入门用户,我想知道如何执行此操作:如何从字符串/整数“创建”字节。 So for example I've: 例如,我有:

string some_byte = "202";

When I would save that byte to a file, I want that the file is 1 byte instead of 3 bytes. 当我将该字节保存到文件时,我希望文件为1字节而不是3字节。 How is that possible? 那怎么可能? Thanks in advance, Tim 预先感谢,蒂姆

I would use C++'s String Stream class <sstream> to convert the string to an unsigned char. 我将使用C ++的String Stream类<sstream>将字符串转换为未签名的char。

And write the unsigned char to a binary file. 并将未签名的char写入二进制文件。

so something like [not real code] 所以像[不是真正的代码]

std::string some_byte = "202";
std::istringstream str(some_byte);
int val;
if( !(str >> val))
{
  // bad conversion
}

if(val > 255)
{
  // too big
}

unsigned char ch = static_cast<unsigned char>(val);

printByteToFile(ch); //print the byte to file.

In C++, casting to/from strings is best done using string streams: 在C ++中,最好使用字符串流完成向字符串的强制转换:

#include <sstream>
// ...
std::istringstream iss(some_string);
unsigned int ui;
iss >> ui;
if(!iss) throw some_exception('"' + some_string + "\" isn't an integer!");
unsigned char byte = i;

To write to a file, you use file streams. 要写入文件,请使用文件流。 However, streams usually write/read their data as strings. 但是,流通常以字符串形式写入/读取数据。 you will have to open the file in binary mode and write binary, too: 您还必须以二进制模式打开文件并编写二进制文件:

#include <fstream>
// ...
std::ofstream ofs("test.bin", std::ios::binary);
ofs.write( reinterpret_cast<const char*>(&byte), sizeof(byte)/sizeof(char) );

The simple answer is... 简单的答案是...

int value = atoi( some_byte ) ;

There are a few other questions though. 但是,还有其他一些问题。

1) What size is an int and is it important? 1)一个int的大小是多少,它重要吗? (for almost all systems it's going to be more than a byte) (对于几乎所有系统,它都将超过一个字节)

int size = sizeof(int) ;

2) Is the Endianness important? 2) Endianness重要吗? (if it is look in to the htons() / ntohs() functions) (如果查看htons()/ ntohs()函数)

Use boost::lexical_cast 使用boost :: lexical_cast

#include "boost/lexical_cast.hpp"
#include <iostream>

int main(int, char**)
{
    int a = boost::lexical_cast<int>("42");
    if(a < 256 && a > 0)
        unsigned char c = static_cast<unsigned char>(a);

}

You'll find the documentation at http://www.boost.org/doc/libs/1_43_0/libs/conversion/lexical_cast.htm 您可以在http://www.boost.org/doc/libs/1_43_0/libs/conversion/lexical_cast.htm中找到该文档

However, if the goal is to save space in a file, I don't think it's the right way to go. 但是,如果目标是节省文件空间,那么我认为这不是正确的方法。 How will your program behave if you want to convert "257" into a byte? 如果要将“ 257”转换为字节,程序的行为如何? Juste go for the simplest. Juste最简单。 You'll work out later any space use concern if it is relevant (thumb rule: always use "int" for integers and not other types unless there is a very specific reason other than early optimization) 如果相关,您将在以后解决任何空间使用问题(经验法则:对于整数而不是其他类型,请始终使用“ int”,除非有除早期优化以外的非常具体的原因)

EDIT As the comments say it, this only works for integers, and switching to bytes won't (it will throw an exception). 编辑正如评论所说,这仅适用于整数,并且切换到字节将不起作用(它将引发异常)。 So what will happen if you try to parse "267"? 那么,如果您尝试解析“ 267”会怎样? IMHO, it should go through an int, and then do some bounds tests, and then only cast into a char. 恕我直言,它应该经过一个int,然后进行一些边界测试,然后仅转换为char。 Going through atoi for example will result extreamly bugs prone. 例如,通过atoi会导致极易出现错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM