Bitwise Operations & Number Systems
| system | digits used | base | example: 42 |
|---|---|---|---|
| decimal (human) | 0 1 2 3 4 5 6 7 8 9 | 10 | 42 |
| binary (computer) | 0 1 | 2 | 0b101010 |
| hexadecimal (compact) | 0–9 A B C D E F | 16 | 0x2A |
Each position is a power of 2. Reading RIGHT to LEFT: 1, 2, 4, 8, 16, 32, 64, 128.
→ a byte = 8 bits. maximum value: 11111111 in binary = 255 in decimal.
The trick: keep dividing by 2. The remainders, read bottom-to-top, give you the binary number.
even / odd check
Instead of n % 2 == 0, use (n & 1) == 0. Last bit of any even number is always 0. This is what low-level code does.
power of 2 check
n & (n-1) == 0 — a power of 2 has exactly one 1-bit. Subtracting 1 flips all bits below it. AND gives 0.
file permission flags (Linux)
chmod 755 is bitwise flags. Read=4, Write=2, Execute=1. OR them: 4|2|1 = 7 = full access.
RGB color masking
Extract red from 0xFF5733: (color >> 16) & 0xFF = 255. Used in every browser and image editor.
multiply / divide by 2 fast
n << 1 = n × 2. n >> 1 = n ÷ 2. Compilers use this internally for speed.
interview patterns (LeetCode)
Single number, counting bits, missing number, subset generation. All use XOR or AND. Once you see the pattern, these become straightforward.