Search code examples
cintegerhextypeconverter

C - Convert long int to signed hex string


MASSIVE EDIT:

I have a long int variable that I need to convert to a signed 24bit hexadecimal string without the "0x" at the start. The string must be 6 characters followed by a string terminator '\0', so leading zeros need to be added.

Examples: [-1 -> FFFFFF] --- [1 -> 000001] --- [71 -> 000047]

Answer This seems to do the trick:

long int number = 37;
char string[7];

snprintf (string, 7, "%lX", number);

Solution

  • Because you only want six digits, you are probably going to have to do some masking to make sure that the number is as you require. Something like this:

    sprintf(buffer, "%06lx", (unsigned long)val & 0xFFFFFFUL);
    

    Be aware that you are mapping all long integers into a small range of representations. You may want to check the number is in a specific range before printing it (E.g. -2^23 < x < 2^23 - 1)