Skip to content

Bit Manipulation - The Low-Level Wizardry

"Bit manipulation là ngôn ngữ của CPU. Hiểu nó = Hiểu máy tính thực sự hoạt động thế nào." - HPN

Tại sao cần Bit Manipulation?

BenefitExample
SpeedBitwise ops nhanh hơn arithmetic 10-100x
MemoryLưu 32 flags trong 1 integer thay vì 32 booleans
CryptographyXOR là foundation của encryption
CompressionHuffman, LZ algorithms
GraphicsColor manipulation, alpha blending

Basic Bitwise Operators

python
# AND (&): 1 if BOTH bits are 1
0b1010 & 0b1100  # = 0b1000 (8)

# OR (|): 1 if ANY bit is 1
0b1010 | 0b1100  # = 0b1110 (14)

# XOR (^): 1 if bits are DIFFERENT
0b1010 ^ 0b1100  # = 0b0110 (6)

# NOT (~): Flip all bits
~0b1010  # = -11 (two's complement)

# Left Shift (<<): Multiply by 2^n
5 << 2  # = 20 (5 * 4)

# Right Shift (>>): Divide by 2^n
20 >> 2  # = 5 (20 / 4)

Module Contents

XOR Magic

  • Swap without temp
  • Find single non-duplicate
  • Missing number in sequence

Bitmasking

  • Subset generation
  • RBAC permissions
  • State compression

Fast Exponentiation

  • A^B % M in O(log B)
  • RSA cryptography foundation
  • Matrix exponentiation

Quick Reference

OperationCodeUse Case
Check bit i(n >> i) & 1Is feature enabled?
Set bit in | (1 << i)Enable feature
Clear bit in & ~(1 << i)Disable feature
Toggle bit in ^ (1 << i)Switch feature
Get lowest set bitn & (-n)Fenwick Tree, LSB
Clear lowest set bitn & (n-1)Count set bits
Check power of 2n & (n-1) == 0Memory alignment
All 1s (n bits)(1 << n) - 1Bitmask

💡 HPN's Rule

"Thấy 'subset', 'XOR', 'flags', 'permissions' → Bit manipulation. Nhanh hơn, gọn hơn, đẹp hơn."