c++ - C++ 中字符串/整数的字节

标签 c++ string char int byte

我是 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/

相关文章:

c++ - 尝试访问二维 vector 元素时出现段错误

algorithm - 堆栈问题 : pop out in a pattern

java - 如何在 Java 中将非常大的字符串转换为数字

c - 使用 C 返回数组

c - 循环问题 - 重复指令两次而不是一次

C++如何在输入字母时停止崩溃

c++ - 插件代码中的公共(public)基类

c++ - 在 CMake 中引入最小的 C++ 标准版本

C 中的带有回文检查器的字符指针

c - 在 C 中通过引用传递 char 数组