Lazer
Lazer

Reputation: 94820

How to display the maximum value of a unsigned long long in C?

What am I doing wrong here?

$ cat size.c
#include<stdio.h>
#include<math.h>

int main() {

printf ("sizeof unsigned int = %d bytes.\n", sizeof(unsigned int));
printf ("sizeof unsigned long long = %d bytes.\n", sizeof(unsigned long long));

printf ("max unsigned int = %d\n", (int)(pow(2, 32) - 1));
printf ("max unsigned long long = %lld\n", (unsigned long long)(pow(2, 64) - 1));

}
$ gcc size.c -o size
$ ./size
sizeof unsigned int = 4 bytes.
sizeof unsigned long long = 8 bytes.
max unsigned int = 2147483647
max unsigned long long = -1
$ 

I am expecting 18446744073709551615 as output instead of a -1 at the last line.


Okay, I completely missed that I was getting the wrong value for 232 - 1, which should have been 4294967295, not 2147483647. Things make more sense now.

Upvotes: 16

Views: 45828

Answers (5)

cyber_raj
cyber_raj

Reputation: 1857

Whoever done -1 to Kiril Kirov post pls take a look here:

Is it safe to use -1 to set all bits to true? Dingo post

In Kiril post only slight modification required regarding sign extension:

unsigned long long ulTestMax = -1LLu; 

-1 is antipattern, it'll do the job if u dont want to go with the solution provided by lmits.h

Upvotes: 1

salezica
salezica

Reputation: 76909

Edit: changed ~0 to (type) -1 as per Christoph's suggestion. See the comments below.

You can get the maximum value of an unsigned type doing the following:

unsigned long long x = (unsigned long long) -1;

Easier, right? =). Second, you are telling printf() to interpret the given variable as a long long decimal, which is signed. Try this instead:

unsigned long long x = (unsigned long long) -1;
printf("%llu", x);

%llu means "long long unsigned".

Upvotes: 3

Kiril Kirov
Kiril Kirov

Reputation: 38163

unsigned long long ulTestMax = -1;
printf ("max unsigned long long = %llu\n", ulTestMax );

this works in C++, should work here, too.

Upvotes: 2

Jens Gustedt
Jens Gustedt

Reputation: 78903

Just don't suppose that it has a certain value use ULLONG_MAX

Upvotes: 29

sepp2k
sepp2k

Reputation: 370122

Use %llu, not %lld. d is for signed integers, so printf displays it as a signed long long.

Upvotes: 19

Related Questions