简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM