What is Bit Manipulation?
Operating on individual bits inside binary numbers.
You’ve already seen XOR. Here are the other common operations.
AND
Both bits must be 1 to get 1.
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
Only 1 AND 1 gives 1. Everything else is 0.
Example:
Compare each column. Both 1? Keep it. Otherwise, 0.
OR
Either bit being 1 gives 1.
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
Only 0 OR 0 gives 0. Everything else is 1.
Example:
NOT
Flip every bit.
1 becomes 0. 0 becomes 1.
Left Shift
Move all bits to the left. Fill the right with 0.
Each left shift multiplies by 2.
Right Shift
Move all bits to the right. Bits on the right fall off.
Each right shift divides by 2 (drops remainder).
Quick Reference
| Operation | Symbol | What it does |
|---|---|---|
| AND | 1 only if both are 1 | |
| OR | 1 if either is 1 | |
| XOR | 1 if different | |
| NOT | Flip all bits | |
| Left shift | Multiply by 2 | |
| Right shift | Divide by 2 |