Reading in binary data and displaying as hex.

Trying to figure out how to read in data from a binary file one byte at a time, then display it in hex. From my googling, I've figured out this much, but when I cast it to an int, it displays the hex values as 4 bytes instead of 1 (so ff is ffffffff). I want it to only display as one byte, and I'd also like it to be in all caps. Anyone know how?

What I've got so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
  ifstream fin( "test.dat", ios::in | ios::binary );
  char data[10];
  if ( fin.is_open() )
    fin.read( data, 10 );
    else
      return -1;

  for ( int i = 0; i < 10; i++ )
    cout << hex << static_cast<int>(data[i]) << " ";

  return 0;
}
Last edited on
To show them in uppercase you can try the format flag "uppercase"
http://www.cplusplus.com/reference/ios/ios_base/fmtflags/

it displays the hex values as 4 bytes instead of 1 (so ff is ffffffff).
That's because of the cast to int.
For signed char 0xFF == -1.
After the cast you end up with an int whose value is -1
For signed int -1 == 0xFFFFFFFF.

Try using unsigned char (to read from ifsteam you might need to cast them to signed).
Last edited on
ff is not ffffffff. Make sure you convert from unsigned char to unsigned int, or you will get sign involved.
It says "invalid conversion from 'unsigned char*' to 'std::basic_istream<char>::char_type* {aka char*}'" when using an unsigned char.

When I cast it to signed char it says "invalid static_cast from type 'unsigned char [10]' to type 'char'|" and if I use a c-style cast it says "cast from 'unsigned char*' to 'char' loses precision"
I never said to change the types of your existing variables - just nest casts.
The error seems to say you're trying to cast an unsigned char[] to signed char. Is that the case?
The error seems to say you're trying to cast an unsigned char[] to signed char. Is that the case?

You said to use unsigned chars, and that I'd have to cast them to signed while reading in from the file. That's what I was trying to do.


cout << hex << static_cast<unsigned int>(static_cast<unsigned char>(data[i])) << " ";
This seems to work, although it seems... unusual. Is it okay to do that?

Edit: Oh wait, that's what L B meant by nest casts?
Last edited on
Yes that's probably it. What I was saying was
1
2
3
4
5
6
7
8
9
ifstream fin( "test.dat", ios::in | ios::binary );
  unsigned char data[10];
  if ( fin.is_open() )
    fin.read(static_cast<char*>(data), 10 );
    else
      return -1;

  for ( int i = 0; i < 10; i++ )
    cout << hex << static_cast<int>(data[i]) << " ";


I didn't test this, so if LB's sugestion works just go with that.
Topic archived. No new replies allowed.