C++中涉及按位运算的表达式的值是多少

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

在我的机器上,下面的表达式:-

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

打印以下内容:-

113
-7296

我试过假设 16 位整数计算出来,但我的答案与按位运算后获得的值不匹配。

这仅仅是未定义行为的情况还是我在这里遗漏了什么?

您可以使用 bitset 检查整数的二进制表示。

程序:

#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";
}

输出:

113
00000000000000000000000001110001
-114
11111111111111111111111110001110
-7296
11111111111111111110001110000000

如您所见,~ 反转所有位。