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

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

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

相关标签:
8条回答
  • 2021-02-04 12:25

    It's just a bitwise-and of the number. Negative numbers are represented as two's complement.

    So for instance, bitwise and of 7&(-7) is x00000111 & x11111001 = x00000001 = 1

    0 讨论(0)
  • 2021-02-04 12:27

    Because x & -x = {0, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 16, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 32} for x from 0 to 32. It is used to jumpy in the for sequences for some applications. The applications can be to store accumulated records.

    for(;x < N;x += x&-x) {
        // do something here
        ++tr[x];
    }
    

    The loop traverses very fast because it looks for the next power of two to jump.

    0 讨论(0)
  • 2021-02-04 12:32

    On pretty much every system that most people actually care about, it will give you the highest power of 2 that n is evenly divisible by.

    0 讨论(0)
  • 2021-02-04 12:34

    I would add a self-explanatory example to the Mark Randsom's wonderful exposition.

    010010000 | +144 ~
    ----------|-------
    101101111 | -145 +
            1 |
    ----------|-------
    101110000 | -144 
    
    101110000 | -144 & 
    010010000 | +144
    ----------|-------
    000010000 |   16`
    
    0 讨论(0)
  • 2021-02-04 12:38

    As @aestrivex has mentioned, it is a way of writing 1.Even i encountered this

    for (int y = x; y > 0; y -= y & -y)
    

    and it just means y=y-1 because
    7&(-7) is x00000111 & x11111001 = x00000001 = 1

    0 讨论(0)
  • 2021-02-04 12:40

    I believe it is a trick to figure out if n is a power of 2. (n == (n & -n)) IFF n is a power of 2 (1,2,4,8).

    0 讨论(0)
提交回复
热议问题