代字号运算符分别返回-1,-2而不是0、1 [英] tilde operator returning -1, -2 instead of 0, 1 respectively
问题描述
我对此感到困惑.我认为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 ~
.
这篇关于代字号运算符分别返回-1,-2而不是0、1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!