tags:

views:

136

answers:

3

How to convert integer to hexadecimal in C?

+5  A: 

Usually with printf (or one of its cousins) using the %x format specifier. Alternatively, strtol specifying the base as 16.

Jerry Coffin
wanna add an example?
Keith Nicholas
@Keith: no -- I'm intentionally giving just enough information to help get somebody started without doing the job for them.
Jerry Coffin
You may want to at least give the signature or a link to a man page for `strtol`.
strager
Thanx..it helped
A: 

http://en.wikipedia.org/wiki/Hexadecimal + http://www.cplusplus.com/reference/clibrary/cstdio/printf/ + http://www.cplusplus.com/doc/hex/ + http://en.wikipedia.org/wiki/Integer . Those should give you all the information you'll ever need about integers, bases and converting between bases in C.

Chinmay Kanchi
+3  A: 

This code

int a = 5;
printf("%x\n", a);

prints

5

This code

int a = 5; 
printf("0x%x\n", a);

prints

0x5

This code

int a = 89778116;
printf("%x\n", a);

prints

559e7c4

If you capitalize the x in the format it capitalizes the hex value:

int a = 89778116;
printf("%X\n", a);

prints

559E7C4

If you want to print pointers you use the p format specifier:

char* str = "foo";
printf("0x%p\n", str);

prints

0x01275744
C Johnson
I would recommend using the `#` modifier instead of writing your own `0x`, especially with `%p` whose behavior is implementation-defined and might already include the `0x` for you.
R..
Might want to mention `snprintf`, too.
strager
Also, the format of your answer is confusing with the alternating blocks. It may be useful to have just one code block with the results as comments after the statement.
strager