The value of the bitwise and (&) positive and negative numbers?

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

+5
source share
7 answers

I believe this is a trick to find out if n is a power of 2. (n == (n and -n)) IFF n is a power of 2 (1,2,4,8).

0
source

This is an old trick that gives a number with one bit in it, the bottom bit that was set to n. At least in two arithmetic arithmetic, which today is almost universal.

, : , 1 ( ). 1, , , ; , . , , - , - , 1 0.

P.S. , , :

n & (~n + 1)
+14

, , 2, n .

+3

- . .

, , 7 & (-7) x00000111 x11111001 = x00000001 = 1

+1

Mark Randsom .

010010000 | +144 ~
----------|-------
101101111 | -145 +
        1 |
----------|-------
101110000 | -144 

101110000 | -144 & 
010010000 | +144
----------|-------
000010000 |   16`
0

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} x 0 32. . .

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

, .

0

@aestrivex, 1.

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

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

-2
source

All Articles