Bhubhu Hbuhdbus
Bhubhu Hbuhdbus

Reputation: 1519

C Programming: Convert Hex Int to Char*

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.

Upvotes: 4

Views: 48557

Answers (4)

Sayed Khalaf
Sayed Khalaf

Reputation: 3

Using the sprintf() function like this -- sprintf(charBuffer, "%x", i); -- I think will work very well.

Upvotes: 0

octopusgrabbus
octopusgrabbus

Reputation: 10695

Using the sprintf() function to convert an integer to hexadecimal should accomplish your task.

Here is an example:

int i = 0x11111111;

char szHexPrintBuf[10];

int ret_code = 0;

ret_code = sprintf(szHexPrintBuf, "%x", i);

if(0 > ret_code)
{ 
   something-bad-happend();
}

Upvotes: 0

dirkgently
dirkgently

Reputation: 111150

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.

Upvotes: 5

Ruben
Ruben

Reputation: 2558

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;

Upvotes: 1

Related Questions