how do I print an unsigned char as hex in c++ using ostream?


I want to work with unsigned 8-bit variables in C++. Either unsigned char or uint8_t do the trick as far as the arithmetic is concerned (which is expected, since AFAIK uint8_t is just an alias for unsigned char, or so the debugger presents it.

The problem is that if I print out the variables using ostream in C++ it treats it as char. If I have:

unsigned char a = 0;
unsigned char b = 0xff;
cout << "a is " << hex << a <<"; b is " << hex << b << endl;

then the output is:

a is ^@; b is 377

instead of

a is 0; b is ff

I tried using uint8_t, but as I mentioned before, that's typedef'ed to unsigned char, so it does the same. How can I print my variables correctly?

Edit: I do this in many places throughout my code. Is there any way I can do this without casting to int each time I want to print?

3/23/2009 12:51:55 PM

Accepted Answer

I would suggest using the following technique:

struct HexCharStruct
  unsigned char c;
  HexCharStruct(unsigned char _c) : c(_c) { }

inline std::ostream& operator<<(std::ostream& o, const HexCharStruct& hs)
  return (o << std::hex << (int)hs.c);

inline HexCharStruct hex(unsigned char _c)
  return HexCharStruct(_c);

int main()
  char a = 131;
  std::cout << hex(a) << std::endl;

It's short to write, has the same efficiency as the original solution and it lets you choose to use the "original" character output. And it's type-safe (not using "evil" macros :-))

7/3/2012 6:32:55 PM


cout << "a is " << hex << (int) a <<"; b is " << hex << (int) b << endl;

And if you want padding with leading zeros then:

#include <iomanip>
cout << "a is " << setw(2) << setfill('0') << hex << (int) a ; 

As we are using C-style casts, why not go the whole hog with terminal C++ badness and use a macro!

#define HEX( x )
   setw(2) << setfill('0') << hex << (int)( x )

you can then say

cout << "a is " << HEX( a );

Edit: Having said that, MartinStettner's solution is much nicer!

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow