Cheetah
Cheetah

Reputation: 14379

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

Upvotes: 9

Views: 18093

Answers (4)

CB Bailey
CB Bailey

Reputation: 791441

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)

Upvotes: 10

Chris Dodd
Chris Dodd

Reputation: 126175

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

Upvotes: 1

user97370
user97370

Reputation:

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

Upvotes: 10

Jakob
Jakob

Reputation: 24360

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

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

Upvotes: 2

Related Questions