Reputation: 323
I'm learning C/C++ and started to try out programing with big numbers but when printing them I get a strange error.
Here is my example code:
unsigned long long shiftresult = 1ULL;
for (int i = 0; i < 64; i++) {
shiftresult = (1ULL << i);
printf("%lld << %d = %lld\n", 1ULL, i, shiftresult);
cout << 1ULL << " << " << i << " = " << shiftresult << endl;
}
The problem being that when the loop reaches i = 63
printf prints -9223372036854775808
while cout prints 9223372036854775808
which is the "real" output.
Could someone explain why this happens?
Upvotes: -2
Views: 113
Reputation: 239652
Because you told printf
to print %lld
(a signed long long
), but your value is actually an unsigned long long
, which should be printed with %llu
. output streams can figure that out automatically, printf
has to be told.
Upvotes: 3
Reputation: 223689
You're using the wrong format specifier for printf
.
The %lld
format specifier expects a long long
argument, but you're passing an unsigned long long
argument, so the unsigned number is being interpreted as a signed number.
You need to use %llu
to print an unsigned long long
.
Upvotes: 6