繁体   English   中英

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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