Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Correct way to print "unsigned long" in hex

Tags:

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.

like image 451
SomethingSomething Avatar asked Apr 08 '15 08:04

SomethingSomething


People also ask

How do I print unsigned long?

%ul will just print unsigned (with %u), and then the letter "l" verbatim. Just as "%uw" will print unsigned, followed by letter "w".

How do I print a 64 bit integer in hex?

basically, use the PRIx64 macro from <inttypes. h> . Use printf("val = %#018"PRIx64"\n", val); to print leading zeros.

Why do we use unsigned long long in C?

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

How do you declare an unsigned long long int?

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.


2 Answers

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

like image 166
unwind Avatar answered Sep 19 '22 11:09

unwind


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

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

like image 32
Himanshu Sourav Avatar answered Sep 22 '22 11:09

Himanshu Sourav