【问题标题】:what is the value of the expression involving bitwise operation in C++C ++中涉及按位运算的表达式的值是多少
【发布时间】:2021-07-28 06:39:14
【问题描述】:

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

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

打印以下内容:-

113
-7296

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

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

【问题讨论】:

  • ~q 反转位,因此最高有效位从 0 反转为 1。对于有符号整数,这使其成为负数。
  • 添加,最高有效位是有符号位,控制值是正数还是负数。
  • 添加到添加,assuming 16-bit integer, 你为什么这么认为?执行std::cout &lt;&lt; sizeof(int),您可能会发现它实际上是 32 位或 64 位。
  • 这就是为什么我尝试只对无符号类型进行位操作。

标签: c++ bit-manipulation bit-shift


【解决方案1】:

您可以使用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

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

【讨论】:

  • 你比我快:P
  • 你下次要快点,:P
猜你喜欢
  • 2022-11-11
  • 2013-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-18
  • 2019-12-05
  • 1970-01-01
相关资源
最近更新 更多