为什么n按位和-n总是返回最右边的位(最后一位) [英] Why n bitwise and -n always return the right most bit (last bit)

查看:68
本文介绍了为什么n按位和-n总是返回最右边的位(最后一位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是python代码段:

Here is the python code snippet:

1 & -1 # 1
2 & -2 # 2
3 & -3 # 1
...

似乎任何 n&-n 总是最右边(最后)返回,我真的不知道为什么.有人可以帮助我了解这一点吗?

It seems any n & -n always return right most (last) bit, I don't really know why. Can someone help me to understand this?

推荐答案

这是由于负数以二进制表示的方式所致,称为二进制补码.

It's due to the way that negative numbers are represented in binary, which is called two's complement representation.

创建数字n的二进制补码(换句话说,创建-n的表示形式):

To create the two's complement of some number n (in other words, to create the representation of -n):

  • 反转所有位
  • 添加1

换句话说,当您编写 1&-1 的意思是 1&((〜1)+1).最初的〜1 给出值 1111110 ,加一个得到的结果就是 11111111 .(在这些示例中,我们坚持使用8位.)将值与 1 进行与"运算仅得到 1 .

So in other words, when you write 1 & -1 it really means 1 & ((~1)+1). The initial ~1 gives the value 1111110 and adding one gives 11111111. (Let's stick with 8 bits for these examples.) ANDing that values with 1 gives just 1.

在接下来的情况下, 2&-2 表示 2&((〜2)+1).反转 2 会得到 11111101 ,加一会得到 11111110 .然后与 2 (二进制的 10 以二进制方式)得到 2 .

In the next case, 2 & -2 means 2 & ((~2)+1). Inverting 2 gives 11111101 and adding one gives 11111110. Then AND with 2 (10 in binary) gives 2.

最后 3&-3 表示 3&((〜3)+1).反转 3 给出 11111100 ,添加 1 给出 11111101 ,并与 3 ( 11 二进制)给出了 1 .

Finally 3 & -3 means 3 & ((~3)+1). Invert 3 gives 11111100, add 1 gives 11111101, and AND with 3 (11 binary) gives 1.

这篇关于为什么n按位和-n总是返回最右边的位(最后一位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆