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

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

我正在编写一个 c++ 程序来读取一个 bin file.The 二进制文件具有以下示例内容。

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 等 **。原因是,我正在尝试将值转换为二进制。所以我想得到 **"10 00 01 02" 的二进制等价物,即 10000000000000000000100000010。但是因为内容被解释为 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 为基数的数字表示形式,包括前导零,你确实可以使用 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();