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
In C and languages based on the C syntax, the prefix 0x means hexadecimal (base 16).
L stands for long ; LL stands for long long type. The number does not need to be hex - it works on decimals and octals as well. 3LL // A decimal constant 3 of type long long 03L // An octal constant 3 of type long 0x3L // A hex constant 3 of type long.
Hexadecimal is a numbering system with base 16. It can be used to represent large numbers with fewer digits. In this system there are 16 symbols or possible digit values from 0 to 9, followed by six alphabetic characters -- A, B, C, D, E and F.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With