gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:41:45 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com