Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming: Convert Hex Int to Char*

Tags:

c

char

int

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.

like image 551
Bhubhu Hbuhdbus Avatar asked Oct 19 '25 14:10

Bhubhu Hbuhdbus


2 Answers

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.

like image 103
dirkgently Avatar answered Oct 22 '25 02:10

dirkgently


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;
like image 33
Ruben Avatar answered Oct 22 '25 02:10

Ruben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!