tags:

views:

3105

answers:

4

I want to do:

int a = 255; 
cout << a;

and have it show FF in the output, how would i do this?

+10  A: 

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.

Greg Hewgill
make sure to `using std::hex;` or `using namespace std;`
rlbond
+8  A: 

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>.

Benoît
+1  A: 

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;
Ashwin
+4  A: 

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.

Daniel
There's long been a printf vs cout battle. Of course, cout has the nice property that it derives from ostream and gets all the abstraction benefits. C has no concept of stream objects and thus printf and fprintf are 2 different commands. Really, it would have been nice in C if stdout were a FILE*. Would have made things easier.
rlbond