Displaying hex for an integer value by cout?

I happened to be at a forum, reading posts and I read that you could do this:

1
2
int a = 100;
printf("0x%X",a);


This would display 0x64
[(100)10 = (64)16]

Anyway, I know that I can call the printf function in C++, but is there a way to do that with cout as well?

Moreover, what if I want it to display 0x0064 (16-bit int format) instead of 0x64?

Say I have 10 different numbers ranging from 0 to 65535 (short int), and I want them to be displayed in hexadecimal, with padded zeros where necessary. How would I do that?

--- without having to write my own function to convert the integers to hex strings and padding zeros by checking length of each string (that sounds fun, but not very subtle).

EDIT: I guess most guys are on holidays and that is why newer posts aren't getting a hearty reception like normal days. :p Happy holidays, and happy belated Christmas to you all. :)
Last edited on
http://www.cplusplus.com/reference/iostream/manipulators/hex/
1
2
3
4
5
6
7
8
#include <iostream>
#include <iomanip>
using namespace std;
int main () {
  int a=665;
  cout <<hex<<"0x"<< a << endl;
  return 0;
}


For padding, see: http://www.cplusplus.com/reference/iostream/manipulators/setfill/ and http://www.cplusplus.com/reference/iostream/manipulators/setw/
Last edited on
Ok. That seems to do good. Thanks a lot. :)
By the way, which one is better? Using namespace std and then cout or simply including cstdio and calling printf? IMO printf is complex and difficult to use, whereas cout is easier to use but works only in C++...
Topic archived. No new replies allowed.