Search code examples
c++bit-manipulationbit-shift

what is the value of the expression involving bitwise operation in C++


On my machine, the following expression:-

int main()
{
    int q = 0b01110001;
    cout << q << endl;
    cout << (~q << 6);
}

prints the following :-

113
-7296

I have tried working it out assuming 16-bit integer, but my answer doesn't match the value obtained after the bitwise operations.

Is it simply a case of undefined behavior or am I missing something here?


Solution

  • You can check binary representation of an integer using bitset.

    Program :

    #include <iostream>
    #include <bitset>
    using namespace std;
    
    int main() {
        int q = 0b01110001;
        cout << q << "\n";
        cout << bitset<(sizeof(int) * 8)>(q) << "\n";
        cout << ~q << "\n";
        cout << bitset<(sizeof(int) * 8)>(~q) << "\n";
        cout << (~q << 6) << "\n";
        cout << bitset<(sizeof(int) * 8)>(~q << 6) << "\n";
    }
    

    Output :

    113
    00000000000000000000000001110001
    -114
    11111111111111111111111110001110
    -7296
    11111111111111111110001110000000
    

    As you can see, ~ inverts all the bits.