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.
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.
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);
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.
Just don't suppose that it has a certain value use ULLONG_MAX
Use %llu
, not %lld
. d
is for signed integers, so printf
displays it as a signed long long.
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".
unsigned long long ulTestMax = -1;
printf ("max unsigned long long = %llu\n", ulTestMax );
this works in C++, should work here, too.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With