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
2009-11-20 23:07:42
+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
2009-11-20 23:09:13
How about `snprintf`? :-)
James McNellis
2009-11-20 23:10:36
I thought `snprintf` is BSD only?
LiraNuna
2009-11-20 23:12:14
It's in the C99 standard library.
James McNellis
2009-11-20 23:13:18
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
2009-11-20 23:15:00
MSVC has a version called `_snprintf`.
Greg Hewgill
2009-11-20 23:19:01
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
2009-11-20 23:27:51
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
2009-11-20 23:32:04
Not to mention no 32bit or 64bit number has 256 hexadecimal digits.
LiraNuna
2009-11-20 23:34:43
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
2009-11-20 23:36:21
`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
2009-11-21 01:22:51
always use "08x" instead "8x"
Arabcoder
2009-11-21 13:17:58
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
2010-01-14 12:07:07