Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unsigned long cannot hold the correct number over 2,147,483,647

Tags:

c++

Source Code:

#include <iostream>
using namespace std;
int main() {
        unsigned long P;

        P = 0x7F << 24;
        cout << P << endl;

        P = 0x80 << 24;
        cout << P << endl;

        return 0;
}

Output:

2130706432
18446744071562067968

As you can see, the first result is correct. But the second result is extremely wrong. The expected result is 2147483648 and it does not match with 18446744071562067968.

I want to know why

like image 493
Akira Tsuchiya Avatar asked Dec 07 '22 10:12

Akira Tsuchiya


1 Answers

The type of the expression 0x80 << 24 is not unsigned long, it’s int. You then assign the result of that expression to P, and in the process convert it to an unsigned long. But at that point it has already overflown (incidentally causing undefined behaviour). Use unsigned long literals in your expression:

P = 0x80ul << 24;
like image 147
Konrad Rudolph Avatar answered Dec 09 '22 23:12

Konrad Rudolph