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
2010-08-12 01:57:08
wanna add an example?
Keith Nicholas
2010-08-12 02:00:27
@Keith: no -- I'm intentionally giving just enough information to help get somebody started without doing the job for them.
Jerry Coffin
2010-08-12 02:20:58
You may want to at least give the signature or a link to a man page for `strtol`.
strager
2010-08-12 04:28:35
Thanx..it helped
2010-08-12 16:37:13
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
2010-08-12 02:16:13
+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
2010-08-12 02:36:39
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..
2010-08-12 03:34:36
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
2010-08-12 04:26:12