Meaning of bitwise and(&) of a positive and negative number?

后端 未结 8 1849
名媛妹妹
名媛妹妹 2021-02-04 11:59

Can anyone help what n&-n means?? And what is the significance of it.

8条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 12:47

    N&(-N) will give you position of the first bit '1' in binary form of N. For example:

    N = 144 (0b10010000) => N&(-N) = 0b10000
    N = 7 (0b00000111) => N&(-N) = 0b1
    

    One application of this trick is to convert an integer to sum of power-of-2. For example:

    To convert 22 = 16 + 4 + 2 = 2^4 + 2^2 + 2^1
    22&(-22) = 2, 22 - 2 = 20
    20&(-20) = 4, 20 - 4 = 16
    16&(-16) = 16, 16 - 16 = 0
    

提交回复
热议问题