26
votes

I have a function that gets an unsigned long variable as parameter and I want to print it in Hex.

What is the correct way to do it?

Currently, I use printf with "%lx"

void printAddress(unsigned long address) {
    printf("%lx\n", address);
}

Should I look for a printf pattern for unsigned long hex? (and not just "long hex" as mentioned above)

Or does printf convert numbers to hex only using the bits? - so I should not care about the sign anyway?

Clarification

This question was rooted in a confusion: hex is another way to express bits, which means that signed/unsigned number is just an interpretation. The fact that the type is unsigned long therefore doesn't change the hex digits. Unsigned just tells you how to interpret those same bits in your computer program.

2
Please consult the friendly documentation. - Kerrek SB
What problem are you facing with %lx ? This should be fine for an unsigned long. Of course if your address parameter really is an address then you should probably be passing it as void * and printing it with %p. - Paul R
What printf lacks is a way to print signed hexadecimal numbers... - rodrigo
Actually I now see that in cplusplus.com it is written very boldly that "x" is unsigned hex. You were right, my question is not very useful... - SomethingSomething
@SomethingSomething: As the accepted answer demonstrates, it is actually exactly trivial, i.e. the manual contains a straight-forward answer to your question. Posting on Stack Overflow added nothing. - Kerrek SB

2 Answers

27
votes

You're doing it right.

From the manual page:

o, u, x, X

The unsigned int argument is converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal (x and X) notation.

So the value for x should always be unsigned. To make it long in size, use:

l

(ell) A following integer conversion corresponds to a long int or unsigned long int argument [...]

So %lx is unsigned long. An address (pointer value), however, should be printed with %p and cast to void *.

6
votes

I think the following format specifier should work give it a try

printf("%#lx\n",address);