Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 553
Lazer Avatar asked Oct 09 '10 20:10

Lazer


People also ask

What is the maximum value of unsigned char in C?

These limits specify that a variable cannot store any value beyond these limits, for example an unsigned character can store up to a maximum value of 255.

How do you print maximum and minimum value of unsigned integer?

printf("%u", ~0); //fills up all bits in an unsigned int with 1 and prints the value. Show activity on this post. printf("%lu",-1);

What is the max value of unsigned int?

The number 4,294,967,295, equivalent to the hexadecimal value FFFF,FFFF16, is the maximum value for a 32-bit unsigned integer in computing.


5 Answers

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

like image 173
Jens Gustedt Avatar answered Oct 05 '22 16:10

Jens Gustedt


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

like image 22
sepp2k Avatar answered Oct 05 '22 16:10

sepp2k


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

like image 20
slezica Avatar answered Oct 05 '22 17:10

slezica


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

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

like image 36
Kiril Kirov Avatar answered Oct 05 '22 17:10

Kiril Kirov


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

like image 35
cyber_raj Avatar answered Oct 05 '22 16:10

cyber_raj