In C++, hex sets the number base of a stream to 16 (hexadecimal). Integers are then printed with the digits 0 to 9 and a to f.
It works for both output and input, and it stays on until you change it with dec or oct. It comes from <ios>, which <iostream> includes.
This is a manipulator. You do not call it on its own. You send it into a stream with << or >>, and it changes how that stream behaves from then on (or does one small job, like ending a line).
In hex, the digits go 0, 1, ..., 9, a, ..., f. So 10 is written as a.
255 is 15 * 16 + 15, which is ff.
4096 is 16 * 16 * 16, so it is written as a one followed by three zeros: 1000.
Example 2 — Read a Hex Number
Use hex on an input stream. A leading 0x is accepted too.
C++
#include <iostream>
#include <sstream>
int main() {
std::istringstream in("ff 0x10");
int a = 0;
int b = 0;
in >> std::hex >> a >> b;
std::cout << std::dec << a << ' ' << b << '\n';
return 0;
}
Output
255 16
How It Works
std::hex makes >> read the text as base 16 numbers.
ff becomes 255. 0x10 is read with its 0x prefix and becomes 16.
The numbers are stored as plain int values. std::dec prints them in the usual form.
Example 3 — Print the Hex Code of a Character
A char must be cast to int, or it prints as a letter.
C++
#include <iostream>
int main() {
char c = 'A';
std::cout << std::hex;
std::cout << c << '\n';
std::cout << static_cast<int>(c) << '\n';
return 0;
}
Output
A
41
How It Works
A char is printed as a character, whatever the base is. The first line is A.
static_cast<int>(c) turns the letter into its code, which is 65 in decimal.
In hex, 65 is 4 * 16 + 1, so the second line is 41.
Frequently Asked Questions
It sets the number base of a stream to 16, so integers are printed and read in hexadecimal.
Use std::hex and std::showbase together: cout << hex << showbase << 255.
Add std::uppercase, for example cout << hex << uppercase << 255 prints FF.
A char is printed as a letter. Cast it to int, as in static_cast<int>(c), to see the number.