简体   繁体   中英

Reading a hex file C++

I am trying to read using the hex format with two characters at a time from a file. The problem is whenever the hex char has a 0 in it it is ignored while printing. ex. 08 just shows up as 8. How can I make sure it doesn't omit 0? Does it involve some kind of bit shifting?

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';
    }
}

If you are going to show only 2 digits numbers, you can enable 1 leading zero to your output:

#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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM