tags:

views:

365

answers:

3

How to cast from hexadecimal to string in C?

+1  A: 

You cannot cast from a number to a string in C. You'll have to call a function for that purpose.

Martinho Fernandes
+9  A: 

You cannot simply 'cast', you will need to use sprintf to do the convertion:

unsigned int hex = 0xABC123FF;
char hexString[256];
sprintf(hexString, "0x%08X", hex);

If you want to 'cast' it to string in order to print it, you can use printf directly:

unsigned int hex = 0xABC123FF;
printf("0x%08X", hex);
LiraNuna
How about `snprintf`? :-)
James McNellis
I thought `snprintf` is BSD only?
LiraNuna
It's in the C99 standard library.
James McNellis
Oh wow, I did not know that. sadly, OP did not give platform/compiler, so I would like to keep it compatible with non-C99 compilers (read as: MSVC).
LiraNuna
MSVC has a version called `_snprintf`.
Greg Hewgill
I should mention that `_snprintf` does *not* nul-terminate the output string if the formatted string is longer than the buffer, so one should wrap `_snprintf` inside a `snprintf` function that calls `_snprintf` and then explicitly terminates the buffer (to make it behave the same as `snprintf` on other platforms).
Greg Hewgill
Yay.. let's complicate the OP's request even more! Look, The OP is most definitely a beginner. Do you want to complicate his understanding by using `#ifdef`'s to re-define `_snprintf` and to handle the problem Greg suggested? I'm sorry, but I won't complicate this answer for a beginner.
LiraNuna
Not to mention no 32bit or 64bit number has 256 hexadecimal digits.
LiraNuna
My comments were not meant for the OP, but rather for people who might come across this page in the future and believe that `sprintf` or `_snprintf` is a good, safe idea.
Greg Hewgill
`sprintf` is perfectly safe when used the way LiraNuna did. An upper bound on the number of digits produced by `%x` can be determined from the range of the input number.
caf
always use "08x" instead "8x"
Arabcoder
A: 

Just stumbled over this old thread. Who says one cannot cast hex to string? That's a lie, I can:

unsigned int hex = 0xABC123FF;
char *str = (char*)&hex;

Okay it doesn't make sense printing it as C string (zero terminated), but I casted it ;)

AndiDog