There is no &-
operator. num - (num&-num)
is num - (num & -num)
, where &
performs the bitwise AND of num
and its negation, -num
.
Consider some number in binary, say 0011 0011 1100 11002 (spaces used for easy visualization). The negative of this is −0011 0011 1100 11002. However, we commonly represent negative numbers using two’s complement, in which a power of two is added. For 16-bit formats, we add 216, which is 1 0000 0000 0000 00002. So, to represent −0011 0011 1100 11002, we use 1 0000 0000 0000 00002 + −0011 0011 1100 11002 = 1100 1100 0011 01002.
Observe what happens in this subtraction, column by column from the right:
- In the rightmost column, we have 0−0, which yields 0.
- The next column also has 0−0, yielding 0.
- The next column has 0−1. This yields 1 with a borrow from the column to the left.
- The next column has 0−1−1 (where the second −1 is the borrow). This yields 0 with another borrow.
- Because the minuend (the number being subtracted from) has all zeros up to that initial 1, this borrow is never satisfied, so it propagates throughout the bits.
Thus the result is:
- Starting at the right, 0s remain 0s.
- The first 1 stays a 1 but starts a borrow chain.
- Because of the borrow, all bits to the left of that flip from 0 to 1 or 1 to 0.
Thus the subtrahend (the number being subtracted) and the result differ in all bits to the left of the first 1. And they both have 0s to the right of the first 1. So the only bit they both have set is that first 1.
Therefore, when two’s complement is in use, the result of num & -num
is the lowest 1 bit that is set in num
.
Then num - (num & -num)
subtracts this bit from num
, leaving it as num
with its lowest 1 bit changed to 0.