0

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

1 Answer 1

1

std::setw does not affect reading of single chars, so you're always reading one at a time.

You read the digits, one by one, as characters.
You print those as unsigned integers (%u does not mean binary, it means unsigned decimal), which gives you the ASCII values (48 - 57).

To get the corresponding integer from each digit, subtract '0' from it.

printf ("got %u\n", c - '0');

If you want to interpret the file as a sequence of two-character hexadecimals, first read two characters into a string, then use a std::istringstream and std::hex to extract the number.

int main(int argc, char *argv[])
{
   std::ifstream hexfile("hex.txt");
   std::string x;
   while (hexfile >> std::setw(2) >> x) {
      std::istringstream y(x);
      unsigned int i;
      y >> std::hex >> i;
      printf ("got %u\n", i);
   }    
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.