Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to printf "unsigned long" in C?

I can never understand how to print unsigned long datatype in C.

Suppose unsigned_foo is an unsigned long, then I try:

  • printf("%lu\n", unsigned_foo)
  • printf("%du\n", unsigned_foo)
  • printf("%ud\n", unsigned_foo)
  • printf("%ll\n", unsigned_foo)
  • printf("%ld\n", unsigned_foo)
  • printf("%dl\n", unsigned_foo)

And all of them print some kind of -123123123 number instead of unsigned long that I have.

like image 663
bodacydo Avatar asked Jul 09 '10 04:07

bodacydo


People also ask

How do I print an 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".

What is unsigned 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 I print unsigned?

To print an unsigned int number, use the %u notation. To print a long value, use the %ld format specifier. You can use the l prefix for x and o, too. So you would use %lx to print a long integer in hexadecimal format and %lo to print in octal format.

How do you use unsigned long long int?

The maximum value that can be stored in unsigned long long int is stored as a constant in <climits> header file whose value can be used as ULLONG_MAX. The minimum value that can be stored in unsigned long long int is zero. In case of overflow or underflow of data type, the value is wrapped around.


2 Answers

%lu is the correct format for unsigned long. Sounds like there are other issues at play here, such as memory corruption or an uninitialized variable. Perhaps show us a larger picture?

like image 193
Thanatos Avatar answered Sep 22 '22 15:09

Thanatos


For int %d

For long int %ld

For long long int %lld

For unsigned long long int %llu

like image 45
Linkon Avatar answered Sep 19 '22 15:09

Linkon