Weird Hex Output

In C++, to output and integer in hex, I’d been taught to do this:

cout << hex << an_integer;

And if I want to show “0x” before the value, I need to do the following:

cout.setf(ios::showbase);
cout << hex << an_integer;

The above code works well for either positive or negative integers, but not the value ZERO. If I run the following code:

#include <iostream>

using namespace std;

int main() {
    cout.setf(ios::showbase); //1
    cout << hex << 100 << endl;
    cout << hex << 0 << endl;
    return 0;
}

I am expecting this:

0x64
0x0

However, the actually output is:

0x64
0

The hex number notation “0x” is missing for the value 0.

I also tried this:

cout.setf(ios::hex | ios::showbase);
cout << 0;

It doesn’t work, neither.

This is weird to me. I am wondering why it is and is there a solution without any “ugly” hacks such look like:

cout << "0x" << hex << an_integer;

Update: After asking some of my friends, the solution above seems to be a decent solution to the goal I want to achieve; otherwise, code might become uglier at end of the day. Why not take it easy?

This entry was posted in Programming and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>