I have a file, containing hexadecimal text and I want to read it as a binary buffer, using std::fstream
example file:
hex.txt
00010203040506070809
reading this should result in reading numbers from 0 to 9.
But the following code does not do what I want.
using std::ifstream;
int main(int argc, char *argv[])
{
ifstream hexfile("hex.txt");
unsigned char c;
while (hexfile >> std::hex >> std::setw(2) >> c) {
printf ("got %u\n",c); //print as binary, not as char
}
hexfile.close();
return 0;
}
Output:
got 48
got 48
got 48
got 49
got 48
got 50
got 48
got 51
got 48
got 52
got 48
got 53
got 48
got 54
got 48
got 55
got 48
got 56
got 48
got 57
And interestingly, replacing unsigned char c; with unsigned int c; results in nothing being printed (maybe filestream returns false even on first read)
What am I doing wrong? std::hex should ensure, that input is interpreted as hexadecimal std::setw(2) should ensure, that 2 characters are read on every iteration