views:

366

answers:

4

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);
+1  A: 

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

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

Jakob
+7  A: 

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

Paul Hankin
Furthermore, you should use `snprintf` rather than `sprintf` if you can.
dreamlax
+4  A: 

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)

Charles Bailey
This is the only *complete* answer right now (the conversion to `unsigned long` is required).
caf
What determines what mapping you append?Say I was after a 32bit (8 character string), what mapping would you add then? (Obviously you'd change the format flags to 08 too)
Ben
Effectively, the mapping is x -> x (mod 2^24), so numbers >2^24 wrap around. With eight character, 32 bit string, it would be x -> x (mod 2^32) whether this is an injection (reversible) depends on how big unsigned long is on the platform in question.
Charles Bailey
A: 

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);
Chris Dodd