从 bin 文件 -c++ 中读取十六进制数字为每个字符 2 位数字
Reading hex numbers as 2 digits per char from bin file -c++
我正在编写一个 c++ 程序来读取 bin 文件。二进制文件具有以下示例内容。
10 00 01 02 20 03 04 40 50 .....
这里的问题是使用正常从bin文件读取的字节10,40,50被正确读取。但是在00,01,02 03的情况下....它们分别读作 0、1、2、3。
但是我希望单个字节 00 01 02 03 等也读取为 00 01 02 03 等**。原因是,我正在尝试将值转换为二进制。所以我想得到10000000000000000000100000010的**"10 00 01 02"的二进制等价物。但是因为内容被解释为 10012,所以我得到了10000000000010010结果。请帮助我解决这个问题。抱歉,如果内容太长。提前谢谢。
我使用了以下代码。 为简单起见,剪短了
fstream fp;
fp.open(binFile, ios::binary | ios::in);
char * buffer = new char[4];
// read data as a block:
fp.read(buffer, 4);
// copied the contents of buffer[] to a string str
stringstream ss;
for (std::string::iterator it = str.begin(); it != str.end(); ++it)
{
ss << std::hex << unsigned(*it);
}
ss >> intvalue; // stores the converted hex value
string binstring = bitset<32>(intvalue).to_string();
cout<<binstring // produces wrong value.
从单个字节转换为更大类型的整数通常使用位移来完成。
unsigned char * buffer = new unsigned char[4];
fp.read(buffer, 4);
uint32_t result = buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3];
如果你想有一个字符串对象(不是数字),其中数字的十六进制表示形式,前导零最多填充 8 个字符的十六进制表示形式,你确实可以使用重载运算符<<
一些iomanip
来打印它。您必须使用十六进制并用前导零打印它。您还必须转换为整数,因为字符的打印方式与字符不同,而不是数字。
std::stringstream ss;
for (size_t i = 0; i < 4; ++i) {
ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(buffer[i]);
}
std::string str(ss.str);
或
std::stringstream ss;
ss << std::hex << std::setw(8) << std::setfill('0') << result;
std::string str(ss.str);
如果你想有一个字符串对象,用 2 表示以 2 为底的数字,包括前导零,你确实可以使用bitset
to_string()
:
for (size_t i = 0; i < 4; ++i) {
std::cout << bitset<8>(buffer[i]).to_string();
}
或再次使用上面的result
:
std::cout << bitset<32>(result).to_string();
相关文章:
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何检查一个c++字符串中有多少相同的字符/数字
- 当我输入字符类型的数字时,为什么我无法获得整数?
- scanf() 只取数字作为输入,避免使用其他字符
- 递归形成字符串中所有数字字符的中间和?
- 首先按给定顺序打印所有数字,然后使用 Array 打印所有字符和其他符号
- 如何在 getline 中删除/忽略超过特定数字的字符?
- C++输出奇怪的字符而不是数字 (Windows)
- 为什么strlen(s)与s的大小不同,为什么cout-char显示的是字符而不是数字
- 如何在C++中有效地将数字值重新分配给字符数组
- 我应该以字符形式存储数字以节省内存吗?
- C++ 从 std::string 中删除所有非数字字符
- 在c++中读取文件时,它如何自动将字符放入字符数组,将数字放入整数变量
- 不反转数字的字符反转
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 如果是数字或字符,请检查输入
- 如何将字符更改为数字?
- 生成随机字符/数字
- 如何将 std::string 中的所有非字母字符(数字和特殊字符)替换为空格
- 字符数字 ['0'.."9'] 需要具有连续的数值吗?