首页 > 解决方案 > 读取十六进制文件 C++

问题描述

我正在尝试使用十六进制格式从文件中一次读取两个字符。问题是每当十六进制字符中包含 0 时,它在打印时都会被忽略。前任。08 只是显示为 8。我怎样才能确保它不会省略 0?它是否涉及某种位移?

std::ifstream stream;
stream.open(file_path, std::ios_base::binary);
if (!stream.bad()) {
std::cout << std::hex;
std::cout.width(2);

    while (!stream.eof()) {
        unsigned char c;
        stream >> c;
        cout << (short)c <<'\n';
    }
}

标签: c++

解决方案


如果您只想显示 2 位数字,则可以在输出中启用 1 前导零:

#include <iomanip>

...

cout << std::hex << setfill('0'); //Set the leading character as a 0

cout << std::setw(2) //If output is less than 2 charaters then it will fill with setfill character
     << 8; //Displays 08

//In your example
unsigned char c;
stream >> c;
cout << std::setw(2) << (short)c <<'\n';

推荐阅读