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.
%lx
? This should be fine for an unsigned long. Of course if youraddress
parameter really is an address then you should probably be passing it asvoid *
and printing it with%p
.address
is not a real pointer in a C program - it is an address of a simulated machine, not always in the same size as a pointer on my machine.printf
lacks is a way to print signed hexadecimal numbers...long
and printing via"%lx:
is undefined behavior. The code need not print based on a sign agnostic bit pattern, nor not print at all, it is UB. With"%lx"
, pass anunsigned long
.