从 bin 文件 -c++ 中读取十六进制数字为每个字符 2 位数字

Reading hex numbers as 2 digits per char from bin file -c++

本文关键字:字符 数字 十六进制数字 文件 bin -c++ 读取      更新时间:2023-10-16

我正在编写一个 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();