What does bitwise and (&) mean?

I had come across a code which had a line: i += i & -i.
I know that & compares two binary numbers, but why is is used in i += i & -i ? What will happen if we just do i+=i ?
Last edited on
bitwise and looks at each bit in the operands and combines them according to the below rules:

0 AND 0 = 0
1 AND 0 = 0
0 AND 1 = 0
1 AND 1 = 1

So for example:
1
2
3
4
5
6
7
8
10 & 3 = 2, because:

   dec | hex | bin
   _______________
   10    0xA    1010
    3    0x3    0011
                &&&&
    2    0x2    0010    


As for i += i & -i... that is stupidly obfuscated and I don't know what they're trying to do with that. The output of i & -i for values 1-8:

1
2
3
4
5
6
7
8
9
10
i -> i&-i
_________
1 -> 1
2 -> 2
3 -> 1
4 -> 4
5 -> 1
6 -> 2
7 -> 1
8 -> 8


Not sure what the point of that is.
Topic archived. No new replies allowed.