Reputation: 87
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';
}
}
Upvotes: 1
Views: 314
Reputation: 815
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';
Upvotes: 2