为什么如果（n和-n）== n那么n是2的幂？

java.util.Random源代码行294说

``if ((n & -n) == n) // ie, n is a power of 2 // rest of the code` `

`((n & -n) == n)`当n是2的幂，或者2的幂的负，或者0。

` ` n 0000100...000 -n 1111100...000 n & -n 0000100...000` `

` `n 0000100...000 inverse n 1111011...111 + 1 two's comp 1111100...000` `

† – 或者是0或者2的幂的负数…如顶部所解释的那样。

` ` n: 00001001000 ~n: 11110110111 -n: 11110111000 // the first 0 bit "absorbed" the +1 ^ | (n & -n) fails to equal n at this bit.` `

` `1 & 1 = 1 1 & 0 = 0 0 & 1 = 0 0 & 0 = 0` `

` `7 = 00000111 -1 = NEG(7) + 1 = 11111000 + 1 = 11111001` `

` `8 = 00001000 -8 = 11110111 + 1 = 11111000 00001000 (8) 11111000 (-8) --------- & 00001000 = 8.` `

`(n & -n)`是n。

` `base 2 base 10 000001 = 1 000010 = 2 000100 = 4 ...` `

` `n base 2 ~n ~n+1 (-n) n&-n 1 000001 111110 111111 000001 2 000010 111101 111110 000010 4 000100 111011 111100 000100 8 001000 110111 111000 001000` `

` `n base 2 ~n ~n+1 (-n) n&-n 1 000001 111110 111111 000001 2 000010 111101 111110 000010 3 000011 111100 111101 000001 4 000100 111011 111100 000100 5 000101 111010 111011 000001 6 000110 111001 111010 000010 7 000111 111000 111001 000001 8 001000 110111 111000 001000` `

` `8 = 0b00001000 -8 = 0b11111000` `

` `Starting: 0b00001000 Flip bits: 0b11110111 (one's complement) Add one: 0b11111000 AND 8 : 0b00001000` `

` `00000...00001 = 2 ^ 0 00000...00010 = 2 ^ 1 00000...00100 = 2 ^ 2 00000...01000 = 2 ^ 3 00000...10000 = 2 ^ 4 and so on ...` `

` `000000...000010000...00000 <<< n & 111111...111110000...00000 <<< -n -------------------------- 000000...000010000...00000 <<< n` `

8在hex= 0x000008

-8hex= 0xFFFFF8

8＆-8 = 0x000008