Question
How can I check if exactly one bit is set in an integer, regardless of its position?
if (n > 0 && (n & (n - 1)) == 0) { /* exactly one bit is set */ }
Answer
To determine if an integer has exactly one bit set, we can utilize a clever bit manipulation technique. This method involves using the properties of binary numbers to ascertain whether exactly one bit position is '1'.
int isSingleBitSet(int n) {
return (n > 0) && ((n & (n - 1)) == 0);
} // Returns 1 if true, 0 otherwise.
Causes
- The integer is greater than zero.
- The expression `n & (n - 1)` evaluates to zero.
Solutions
- Use the expression `n > 0 && (n & (n - 1)) == 0` to check for a single bit set.
- If true, it means there's exactly one bit set in the integer.
Common Mistakes
Mistake: Assuming negative integers can be checked the same way.
Solution: Only perform the check for non-negative integers, as the leading bit in a negative integer can affect the result.
Mistake: Not using parentheses correctly in bit operations.
Solution: Ensure correct precedence in operations to prevent logical errors.
Helpers
- single bit set
- check if bit is set
- integer bit manipulation
- programming integer check