Math Fundamentals18 sections · 814 units
Open in Course

Power of Two - The Bit Pattern

Single 1 bit

A power of two has exactly one 1 bit in its binary representation. You already know a trick to count 1 bits: n&(n1)n \& (n - 1) flips the rightmost 1 to 0.

If nn is a power of two, it has one 1 bit. Flipping that bit gives 0. So n&(n1)=0n \& (n - 1) = 0 if and only if nn is a power of two (and n>0n > 0, because 0 is not a power of two).

Example: 16=1000016 = 10000. 161=15=0111116 - 1 = 15 = 01111. 16&15=00000=016 \& 15 = 00000 = 0. For 6=1106 = 110: 61=5=1016 - 1 = 5 = 101. 6&5=10006 \& 5 = 100 \neq 0. This test is O(1)O(1) and uses one bitwise operation.