1

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';
    }
}
  • 3
    Hint: Set your string formatting options on the stream. The default presentation omits leading zeroes, but you can set zero-padding to arbitrary sizes. – tadman Oct 30 '19 at 22:42
  • 2
    Unrelated: Careful with `while (!stream.eof())`. [It doesn't work](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons). – user4581301 Oct 30 '19 at 22:55

1 Answers1

2

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';
Gerard097
  • 805
  • 4
  • 12