问题描述
在我的机器上,以下表达式:-
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
如您所见,~
反转所有位。