C++ cout hex values?

Solution 1:

Use:

#include <iostream>

...

std::cout << std::hex << a;

There are many other options to control the exact formatting of the output number, such as leading zeros and upper/lower case.

Solution 2:

std::hex is defined in <ios> which is included by <iostream>. But to use things like std::setprecision/std::setw/std::setfill/etc you have to include <iomanip>.

Solution 3:

To manipulate the stream to print in hexadecimal use the hex manipulator:

cout << hex << a;

By default the hexadecimal characters are output in lowercase. To change it to uppercase use the uppercase manipulator:

cout << hex << uppercase << a;

To later change the output back to lowercase, use the nouppercase manipulator:

cout << nouppercase << b;

Solution 4:

If you want to print a single hex number, and then revert back to decimal you can use this:

std::cout << std::hex << num << std::dec << std::endl;