在 Java 的 &= -a 中会发生什么

what happens in a &= -a with Java

我看到这条评论,但不明白。

获取它的最后一个设置位

diff &= -diff;

我试过了

int a = 3 & -3; it returns 1.
int a = 2 & -2; it returns 2.
int a = 4 & -4; it returns 4.
int a = 5 & -5; it returns 1.

评论最好用'Get the least significant bit set'表示。要了解发生了什么,您需要检查负数是如何用二进制表示的。该技术称为二进制补码,从数字的正表示开始工作;你补充每一位(即 1 -> 0 和 0 -> 1)。然后将此数字加 1。在12的例子中:

00001100 12
11110011 complement
00000001 binary 1
11110100 add to complement to form twos complement negative

如果您现在将原始值与负值相乘,您将得到

00000100 

其中唯一的位集对应于原始模式中的最低有效位集。

如评论所述,diff & -diff returns diff 上设置的最后一位的值。例如:

diff = 14
.... = 1110 (binary)
....     ^ last set bit
.... 10 is the last set bit
.... 10 in decimal is 2

另一个例子

diff = 24
.... = 11000 (binary)
....    ^ last set bit
.... 1000 is the last set bit
.... 1000 in decimal is 8

我建议阅读有关如何提出精心设计的问题的指南。我个人可以给出的一个建议是在你的问题末尾用一句话准确概括你想知道的内容。