简体   繁体   English

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

[英]tilde operator returning -1, -2 instead of 0, 1 respectively

I'm kind of puzzled by this. 我对此感到困惑。 I thought the ~ operator in C++ was supposed to work differently (not so Matlab-y). 我认为C ++中的〜运算符应该以不同的方式工作(不是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;
}

And here's my output: 这是我的输出:

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

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. 请注意,即使您以bool开头,operator ~也会通过整数提升规则将值提升为int If you need to invert a bool to a bool , use operator ! 如果你需要将bool反转为bool ,请使用operator ! instead of ~ . 而不是~

~ is bitwise NOT operator which means it flips all the bits. 〜是按位NOT运算符,这意味着它会翻转所有位。 For boolean NOT, you should be using ! 对于布尔值NOT,你应该使用! operator 操作者

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

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