C Programming: Convert Hex Int to Char*
36,543
Solution 1
itoa
is non-standard. Stay away.
One possibility is to use sprintf
and the proper format specifier for hexa i.e. x
and do:
char str[ BIG_ENOUGH + 1 ];
sprintf(str,"%x",value);
However, the problem with this computing the size of the value
array. You have to do with some guesses and FAQ 12.21 is a good starting point.
The number of characters required to represent a number in any base b
can be approximated by the following formula:
⌈logb(n + 1)⌉
Add a couple more to hold the 0x
, if need be, and then your BIG_ENOUGH
is ready.
Solution 2
char buffer[20];
Then:
sprintf(buffer, "%x", i);
Or:
itoa(i, buffer, 16);
Character pointer to buffer can be buffer
itself (but it is const) or other variable:
char *p = buffer;
Author by
Bhubhu Hbuhdbus
Updated on July 15, 2020Comments
-
Bhubhu Hbuhdbus almost 4 years
My question is how I would go about converting something like:
int i = 0x11111111;
to a character pointer? I tried using the itoa() function but it gave me a floating-point exception.
-
Ruben almost 12 yearsFor int (4 bytes) sufficient size is easily determinated: 9 for hex, 11 for decimal, 33 for binary.
-
dirkgently almost 12 years@Ruben: Without the
0x
prefix for hex, yes. -
Ruben almost 12 yearsOf cource, without prefix - only for number itself and \0 at the end of string.
-
Ben Voigt almost 12 years@octopusgrabbus: Why did you add a cast? It provides no benefit at all, and is potentially harmful (disabling useful compiler warnings that would catch type errors during compile instead of crashing at runtime).
-
octopusgrabbus almost 12 years@BenVoigt Thanks for catching this. I don't program enough in C anymore and just plain forgot that rule.
-
octopusgrabbus almost 12 yearsThe edit you approved @BenVoigt was rejected. I just submitted again.
-
Robaticus almost 12 yearsI rolled back this answer. @octopusgrabbus - if you want to answer a question, please do so as an answer. Please don't edit another answer to add your own code.