Question

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);
Was it helpful?

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)

OTHER TIPS

Look at sprintf. The %lx specifier does what you want.

Use itoa. It takes the desired base as an argument.

Or on second thought, no. Use sprintf, which is standard-compliant.

In the title you say you want a signed hex string, but all your examples are unsigned hex strings. Assuming the examples are what you want, the easiest way is

sprintf(buffer, "%06X", (int)value & 0xffffff);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top