为什么" I和(ⅰ^(I - 1))"等同于QUOT; I和(-i)QUOT; [英] Why is "i & (i ^ (i - 1))" equivalent to "i & (-i)"
问题描述
我在code的一部分有这个。任何人都可以解释如何 I和(I ^(I - 1))
可降低到 I和(-i)
?
I had this in part of the code. Could anyone explain how i & (i ^ (i - 1))
could be reduced to i & (-i)
?
推荐答案
I ^(I - 1)
使得所有位在最后1位的我变成1。
例如,如果 I
有一个二进制重新presentation为 ABC ... DE10 ... 0
然后 I - 1
将 ABC ... DE01 ...... 1
二进制。从i减去1时,在该部分彼此返回0 ING最后1位之前的部分没有改变,所以 XOR
,而剩下的将是1因为在差I
和 I - 1
。之后, I和(I ^(I - 1))
将得到我的最后1位
For example if i
has a binary representation as abc...de10...0
then i - 1
will be abc...de01...1
in binary. The part before the last 1 bit is not changed when subtracting 1 from i, so xor
ing with each other returns 0 in that part, while the remaining will be 1 because of the difference in i
and i - 1
. After that i & (i ^ (i - 1))
will get the last 1 bit of i
-i
将所有反位到最后1位的i因为在补 -i ==〜I + 1
和 I和(-i)
结果像上面一样
-i
will inverse all bits up to the last 1 bit of i because in two's complement -i == ~i + 1
, and i & (-i)
results the same like the above
例如:
20 = 0001 0100
19 = 0001 0011
20 ^ 19 = 0000 0111 = 7
20 & 7 = 0000 0100
-20 = 1110 1100
20 & -20 = 0000 0100
这篇关于为什么" I和(ⅰ^(I - 1))"等同于QUOT; I和(-i)QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!