波浪号运算符分别返回 -1、-2 而不是 0、1

2022-01-19 00:00:00 boolean c++ tilde

我对此感到有些困惑.我认为 C++ 中的 ~ 运算符应该以不同的方式工作(不是 Matlab-y).这是一个最小的工作示例:

I'm kind of puzzled by this. I thought the ~ operator in C++ was supposed to work differently (not so Matlab-y). Here's a minimum working example:

#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
    bool banana = true;
    bool peach = false;
    cout << banana << ~banana << endl;
    cout << peach << ~peach << endl;
}

这是我的输出:

1-2
0-1

我希望有人对此有所了解.

I hope someone will have some insight into this.

推荐答案

这正是应该发生的事情:当你反转零的二进制表示时,你得到负一;当你反转一的二进制表示时,你会在二进制补码表示中得到负二.

This is exactly what should happen: when you invert the binary representation of zero, you get negative one; when you invert binary representation of one, you get negative two in two's complement representation.

00000000 --> ~ --> 11111111 // This is -1
00000001 --> ~ --> 11111110 // This is -2

请注意,即使您以 bool 开头,运算符 ~ 也会根据整数规则将值提升为 int促销.如果您需要将 bool 反转为 bool,请使用运算符 ! 而不是 ~.

Note that even though you start with a bool, operator ~ causes the value to be promoted to an int by the rules of integer promotions. If you need to invert a bool to a bool, use operator ! instead of ~.

相关文章