I want to do:
int a = 255;
cout << a;
and have it show FF in the output, how would i do this?
I want to do:
int a = 255;
cout << a;
and have it show FF in the output, how would i do this?
Use:
#include <iomanip>
...
cout << hex << a;
There are many other options to control the exact formatting of the output number, such as leading zeros and upper/lower case.
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>
.
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;
I understand this isn't what OP asked for, but I still think it is worth to point out how to do it with printf. I almost always prefer using it over std::cout (even with no previous C background).
printf("%.2X", a);
'2' defines the precision, 'X' or 'x' defines case.