代字号运算符分别返回-1,-2而不是0、1

问题描述:

我对此感到困惑.我认为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 ~.