User Tools

Site Tools


programming:streaming_hex_cxx

Streaming single-byte values in C++

Streaming single-byte values in the hex format is not as simple as it would seem. Maybe everybody knows it already, but if not, here is the solution.

The first approach that comes to mind would be this:

unsigned char b = 130;
...
cout << setw(2) << setfill('0') << hex << b << endl;

Unfortunately, this would print a character representation of the number and the hex statement would be ignored. Contrary to this, following approach wouldn't work either.

cout << setw(2) << setfill('0') << hex << (short int) b << endl;

This would print OK, but if the b is greater than 128, it would be considered negative and the hex value would be prefixed with several ffs (depending of the size of the casted type), which is not what you want.

The only working solution is the following static cast:

cout << setw(2) << setfill('0') << hex << int(static_cast(s[i])) << endl;
programming/streaming_hex_cxx.txt · Last modified: 2017/05/16 11:10 (external edit)