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