Reputation: 12178
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?
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.
Upvotes: 45
Views: 114536
Reputation: 710
I think the following format specifier should work give it a try
printf("%#lx\n",address);
Upvotes: 11
Reputation: 399703
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 *
.
Upvotes: 45