我是 C++ 的初级用户,我想知道如何执行此操作: 我怎样才能从字符串/整数中“创建”一个字节。例如,我有:
string some_byte = "202";
当我将该字节保存到文件时,我希望该文件是 1 个字节而不是 3 个字节。 这怎么可能? 提前致谢, 蒂姆
最佳答案
我会使用 C++ 的字符串流类 <sstream>
将字符串转换为无符号字符。
并将unsigned char写入二进制文件。
所以像[不是真正的代码]
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.
关于c++ - C++ 中字符串/整数的字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2951464/