Why if (n & -n) == n then n is a power of 2?
Because in 2’s complement, -n is ~n+1. If n is a power of 2, then it only has one bit set. So ~n has all the bits set except that one. Add 1, and you set the special bit again, ensuring that n & (that thing) is equal to n. The converse is also true … Read more