Alex Rivera | Logout

c++ hex number format

Asked 2009-10-25T00:52:27.987
10

I'm trying to output the hex value of a char and format it in a nice way.

Required: 0x01 : value 0x1

All I can get is: 00x1 : value 0x1 // or 0x1 if i don't use iomanip

Here's the code i have, 'ch' was declared to be a unsigned char. Is there any other way to do it other than checking the value and manually add an '0'??

cout << showbase;
cout << hex << setw(2) << setfill('0') << (int) ch;

Edit:

I found one solution online:

cout << internal << setw(4) << setfill('0') << hex << (int) ch
Edit
Report

1 Answer

0

In one on my projects I did this:

ostream &operator<<(ostream &stream, byte value)
{
     stream << "0x" << hex << (int)value;
     return stream;
}

I surchaged the operator<< for stream output, and anything that was a byte was shown in hexadecimal. byte is a typedef for unsigned char.

answered 2009-10-25T01:44:35.853

Your Answer