Overview
Bit manipulation — binary level pe directly kaam karo. Fast, memory efficient, interviews mein common hai.
Analogy
Jaise binary switch panel — har switch on/off hai, combinations se magic karo.
Step-by-step
- AND (&): dono bits 1 toh 1 — masking ke liye
- OR (|): koi bhi 1 toh 1 — set bits ke liye
- XOR (^): different bits 1 — toggle/cancel ke liye
- Left shift (<<): multiply by 2, Right shift (>>): divide by 2
Visual
5 = 101
3 = 011
5 & 3 = 001 = 1
5 | 3 = 111 = 7
5 ^ 3 = 110 = 6
5 << 1 = 1010 = 10
Common mistakes
- Operator precedence — bit ops low priority hain, parentheses use karo
- Python mein negative integers two's complement infinite precision
- Java/C mein ~ aur Python mein ~ alag behave karte hain
Practice questions
- Check karo number power of 2 hai ya nahi: n & (n-1) == 0
- Count set bits (Hamming weight) implement karo