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.
%ul will just print unsigned (with %u), and then the letter "l" verbatim. Just as "%uw" will print unsigned, followed by letter "w".
basically, use the PRIx64 macro from <inttypes. h> . Use printf("val = %#018"PRIx64"\n", val); to print leading zeros.
Unsigned long variables are extended size variables for number storage, and store 32 bits (4 bytes). Unlike standard longs unsigned longs won't store negative numbers, making their range from 0 to 4,294,967,295 (2^32 - 1).
Simply write long long int for a signed integer, or unsigned long long int for an unsigned integer. To make an integer constant of type long long int , add the suffix ` LL ' to the integer. To make an integer constant of type unsigned long long int , add the suffix ` ULL ' to the integer.
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 *
.
I think the following format specifier should work give it a try
printf("%#lx\n",address);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With