c++ hex number format
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
std::cout << "0x" << std::noshowbase << std::hex << std::setw(2) << std::setfill('0') << (int)ch;
Since setw
pads out to the left of the overall printed number (after showbase
is applied), showbase
isn't usable in your case. Instead, manually print out the base as shown above.
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.
精彩评论