Reputation: 1096
Shouldn't the following program print out the value of 2^64 -1 as an integer?
#include <stdio.h>
#include <math.h>
int main(void)
{
printf ("%llu\n" , ( unsigned long long int ) ( pow (2 , 8 * sizeof (unsigned long long) ) - 1 ) ) ;
return 0;
}
Upvotes: 1
Views: 49
Reputation: 29126
The function pow
returns a double
, usually a 64-bit floating-point type with 53 bits of mantissa. That is not enough to resolve numbers in the vicinity of 264 with a granularity of 1.
The next representable double
value smaller than 264 is 264 − 2048 = 264 − 211. 264 − 1 is still 264, which is the nearest representable value. Converting that to unsigned long long
, you get 0.
If you need the value of the largest possible unsigned long long
, you can use ULLONG_MAX
from <limits.h>
:
printf ("%llu\n", ULLONG_MAX); // need <limits.h>
The one's complement of (unsigned long long) 0
– an unsigned long long
with all bits set – should work, too:
printf ("%llu\n", ~0ull);
Upvotes: 3