为什么C#中-3==~2
无法理解。为什么输出是“相等”
代码:
if (-3 == ~2)
Console.WriteLine("equal");
else
Console.WriteLine("not equal");
输出:
equal
Unable to understand. Why output is "equal"
code:
if (-3 == ~2)
Console.WriteLine("equal");
else
Console.WriteLine("not equal");
output:
equal
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
因为二进制补码位算术使得它如此
从维基百科页面抄袭并扩展:
所以你得到:
正如您所看到的,所有位都被翻转,这就是 按位非运算符 (
~
) 可以。Because two's complement bit-arithmetic makes it so
Cribbed from the wikipedia page and expanded:
So you get:
And as you can see, all the bits are flipped, which is what the bitwise NOT operator (
~
) does.这篇 stackoverflow 帖子解释了原因:
枚举定义中的波浪号 (~) 是什么?
This stackoverflow post explains why:
What is the tilde (~) in the enum definition?
这是由于有符号整数的二进制补码表示形式: http://en.wikipedia.org/wiki/Twos_complement< /a>
It's due to the two's complement representation of signed integers: http://en.wikipedia.org/wiki/Twos_complement
因为它使用二进制补码。
Because it uses two's complement.
这两个运营商之间有很大的区别。
msdn
There is a big difference between these two operators.
msdn
3 的补码是:
1...1101
2 的(有符号)补码是:
1...1101
很容易做到:
补码:翻转位。
二进制补码:一个补码 + 1。
为什么这有用?计算机可以通过简单的位翻转和加法来进行数字减法。
The two's complement of 3 is:
1...1101
The (signed) one's complement of 2 is:
1...1101
It's easy to do:
One's complement: Flip the bits.
Two's complement: One's complement + 1.
Why is this useful? Computers can subtract numbers by simply bit flipping and adding.