Recognizing a Power of Two as a Bit Pattern
A positive power of two has exactly one set bit in binary. Other positive integers represent a sum of more than one power.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Work a short comparison
Eight is 1000 and twelve is 1100. Subtracting one from eight yields 0111, so the old and changed patterns share no set bit. At twelve, 1100 and 1011 still share a leading bit. Bitwise and detects that difference.
Check zero separately
Zero has no set bit and is not a positive power of two. A formula using AND with one less also yields zero there. Boundary tests separate zero from valid powers.[1]
Use the single-set-bit property on a positive input
Every positive power of two has exactly one set bit. The operation \(n\mathbin{\&}(n-1)\) clears the lowest set bit, so its result is zero for a positive value exactly when that bit was alone. See counting set bits.
8: 1000 AND 0111 = 0000 → yes
12: 1100 AND 1011 = 1000 → no
1: 0001 AND 0000 = 0000 → yes
Add the domain check that the bit relation alone misses
Zero can satisfy the zero-result test even though it is not a positive power of two. A negative minimum in a particular signed width can also have one set bit. Specify the intended number domain and test both.