为什么-3 ==〜2在C# [英] why -3==~2 in C#
本文介绍了为什么-3 ==〜2在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
无法理解。为什么输出是平等
代码:
如果(-3〜== 2)
Console.WriteLine(相等);
,否则
Console.WriteLine(不等于);
输出:
等于
解决方案
由于补位运算使得它如此
从维基百科页面Cribbed和扩展:
最
重大
位6 5 4 3 2 1 0价值
0 0 0 0 0 0 1 1 3
0 0 0 0 0 0 1 0 2
0 0 0 0 0 0 0 1 1
0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 -1
1 1 1 1 1 1 1 0 -2
1 1 1 1 1 1 0 1 -3
1 1 1 1 1 1 0 0 -4
所以,你得到:
0 0 0 0 0 0 1 0 = 2
1 1 1 1 1 1 0 1 = -3
和,你可以看到,所有的位翻转,这是什么的按位NOT运算符(〜
)一样。
Unable to understand. Why output is "equal"
code:
if (-3 == ~2)
Console.WriteLine("equal");
else
Console.WriteLine("not equal");
output:
equal
解决方案
Because two's complement bit-arithmetic makes it so
Cribbed from the wikipedia page and expanded:
Most
Significant
Bit 6 5 4 3 2 1 0 Value
0 0 0 0 0 0 1 1 3
0 0 0 0 0 0 1 0 2
0 0 0 0 0 0 0 1 1
0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 -1
1 1 1 1 1 1 1 0 -2
1 1 1 1 1 1 0 1 -3
1 1 1 1 1 1 0 0 -4
So you get:
0 0 0 0 0 0 1 0 = 2
1 1 1 1 1 1 0 1 = -3
And as you can see, all the bits are flipped, which is what the bitwise NOT operator (~
) does.
这篇关于为什么-3 ==〜2在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文