How can I print 0x0a, instead of 0xa using cout?
#include <iostream>
using std::cout;
using std::endl;
using std::hex;
int main()
{
cout << hex << showbase << 10 << endl;
}
How can I print 0x0a, instead of 0xa using cout?
#include <iostream>
using std::cout;
using std::endl;
using std::hex;
int main()
{
cout << hex << showbase << 10 << endl;
}
Print any number to hex with auto-padding '0' or set. Template allows any data type (e.g. uint8_t)
Example:
Output:
try this.. you simply prepend zeroes based on magnitude.
You can easily modify this to work with larger numbers.
Factor is 16 (for one hex-digit):
16, 256, 4096, 65536, 1048576, ..
respective
0x10, 0x100, 0x1000, 0x10000, 0x100000, ..
Therefore you could also write like this..
And so on.. :P
The important thing that the answer is missing is that you must use
right
with all of the above mentioned flags:To shorten things up for outputting hex, I made a simple macro
then
If you want to make an easier way to output a hex number, you could write a function like this:
Updated version is presented below; there are two ways the
0x
base indicator can be inserted, with footnotes detailing the differences between them. The original version is preserved at the bottom of the answer, so as not to inconvenience anyone that was using it.Note that both the updated and original versions may need some tailoring for systems where the byte size is a multiple of 9 bits.
It can be used as follows:
See both options (as detailed in footnotes, below) live: here.
Footnotes:
This line is responsible for showing the base, and can be either of the following:
The first option will display improperly for custom types that try to output negative hex numbers as
-0x##
instead of as<complement of 0x##>
, with the sign displaying after the base (as0x-##
) instead of before it. This is very rarely an issue, so I personally prefer this option.If this is an issue, then when using these types, you can check for negativity before outputting the base, then using
abs()
(or a customabs()
that returns an unsigned value, if you need to be able to handle the most-negative values on a 2's complement system) onval
.The second option will omit the base when
val == 0
, displaying (e.g., forint
, whereint
is 32 bits)0000000000
instead of the expected0x00000000
. This is due to theshowbase
flag being treated likeprintf()
's#
modifier internally.If this is an issue, you can check whether
val == 0
, and apply special handling when it does.Depending on which option was chosen for showing the base, two lines will need to be changed.
<< "0x"
, thenHEX_BASE_CHARS
is unnecessary, and can be omitted.If using
<< std::showbase
, then the value supplied tosetw()
needs to account for this:The original version is as follows:
Which can then be used like this:
Working example: here.
Use setw and setfill from iomanip
Personally, the stateful nature of iostreams always annoys me. I think boost format is a better option, so I'd recommended the other answer.