Bit Operations
Bit manipulation allows us to perform operations directly on the binary representation of numbers, leading to efficient and elegant solutions.
Why Bit Manipulation?
- Efficiency: Bit operations are extremely fast.
- Memory: Can represent multiple boolean states in a single integer.
- Common Use Cases: Permissions, flags, cryptography, compression, optimization problems.
Common Bit Operations
1. Check if K-th bit is set
To check if the K-th bit (0-indexed from right) is set:
2. Set K-th bit
To set the K-th bit:
3. Clear K-th bit
To clear the K-th bit:
4. Toggle K-th bit
To flip the K-th bit:
5. Toggle rightmost set bit
To toggle (unset) the rightmost set bit:
6. Isolate rightmost set bit
To get a number with only the rightmost set bit:
7. Is power of 2
Check if a number is a power of 2:
8. Modulo (Power of 2)
Efficient modulo when divisor is a power of 2:
9. Count set bits (Brian Kernighan's Algorithm)
Count the number of 1s in the binary representation: