Math Fundamentals18 sections · 814 units
Open in Course

Power of Two - The Idea

Single bit set

Powers of two in binary have exactly one bit set. For example: 1=000121 = 0001_2, 2=001022 = 0010_2, 4=010024 = 0100_2, 8=100028 = 1000_2. All other numbers have multiple bits set or zero bits.

If nn is a power of two, then n1n - 1 flips all bits after the single set bit. For n=8=10002n = 8 = 1000_2, n1=7=01112n - 1 = 7 = 0111_2. Notice n(n1)=00002=0n \land (n - 1) = 0000_2 = 0.

The boolean condition: n > 0 && (n & (n - 1)) == 0. The first part handles negative numbers and zero. The second checks the bit pattern. Both must be true.