Why is “i & (i ^ (i - 1))” equivalent to “i & (-i)”

馋奶兔 提交于 2019-12-17 17:10:14

问题


I had this in part of the code. Could anyone explain how i & (i ^ (i - 1)) could be reduced to i & (-i)?


回答1:


i ^ (i - 1) makes all bits after the last 1 bit of i becomes 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 xoring 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 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

For example:

      20 = 0001 0100
      19 = 0001 0011
 20 ^ 19 = 0000 0111 = 7
 20 & 7  = 0000 0100

     -20 = 1110 1100
20 & -20 = 0000 0100


来源:https://stackoverflow.com/questions/24772669/why-is-i-i-i-1-equivalent-to-i-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!