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
如您所见,~反转所有位。