C – Correct Way to Print ‘unsigned long’ in Hex

c++printf

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?

Edit/Clarification

This question was rooted in a confusion: hex is just 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.

Best Answer

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 *.