how to print hex number.

how to print hex numbers in c++.

i can easily do this in C like this....
1
2
int x=255;
printf("%X",x);

and this will output FF.

how to do this in C++?
1
2
3
4
5
6
7
8
#include <iostream>
#include <iomanip> // This might be necessary

int main()
{
  int x = 255;
  std::cout << std::hex << x << std::endl;
}
If you want FF rather than ff, you need to use std::uppercase, too

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <iomanip>

int main()
{
  int x = 255;

  std::cout << std::hex << x << std::dec << std::endl;
  std::cout << std::hex << std::uppercase << x << std::nouppercase << std::dec << std::endl;

  return 0;
}


ff
FF

(Note I've added std::dec -- and std::nouppercase -- immediately after I'd finished outputting the numbers, so I know the formatting is going to be back to the default for future insertions. If I was writing a hex editor, I'd use std::hex, etc. once, as a distinct init step, to make hex the default.)

When I output hex numbers, I like to display the prefix. This involves a bit more work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <iomanip>

int main()
{
    using namespace std;

    int x =   2;
    int y = 255;

    cout << showbase // show the 0x prefix
         << internal // fill between the prefix and the number
         << setfill('0'); // fill with 0s

    cout << hex << setw(4) << x << dec << " = " << setw(3) << x << endl;
    cout << hex << setw(4) << y << dec << " = " << setw(3) << y << endl;

    return 0;
}


0x02 = 002
0xff = 255

Unfortunately, uppercase causes the Ox prefix to become 0X, so if I want uppercase hex, I alter the code to output the 0x explicitly, and omit the showbase.

Andy

P.S. If you do a lot of formatting changes, it can be easier to cache the formatting flags, etc. and restore them afterwards (or an equivalent class, if you want to be tidier)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void WriteLotsOfOutput()
{
    using namespace std;

    ios_base::fmtflags oldFlags = cout.flags();
    streamsize         oldPrec  = cout.precision();
    char               oldFill  = cout.fill();

    // Do lots of output

    cout.flags(oldFlags);
    cout.precision(oldPrec);
    cout.fill(oldFill);
}


thank you everyone for solving my problem. ;-)

Topic archived. No new replies allowed.