Math Fundamentals18 sections · 814 units
Open in Course

Isolating the Rightmost Set Bit

Another useful trick

Sometimes you need to isolate the rightmost set bit, turning off all others. The formula is n&(n)n \& (-n).

Why does this work? In two's complement representation, n-n is computed as n+1\sim n + 1. When you add 1 to n\sim n, it flips all the trailing 0s in nn to 1s and the rightmost 1 to 0, then carries over. ANDing nn with this isolates just that rightmost 1 bit.

Example: n=12=1100n = 12 = 1100. Then n=12=...0100-n = -12 = ...0100 (in two's complement, focusing on the low bits). n&(n)=1100&0100=0100=4n \& (-n) = 1100 \& 0100 = 0100 = 4. Only the rightmost set bit remains.