Bit manipulationAnimated
Gray Code Generation
Sequence where neighbours differ by one bit: g = i ^ (i >> 1).
Time
O(2ⁿ)
Extra space
O(2ⁿ)
Use it for
Rotary encoders, error reduction.
How it works
- A Gray code lists all n-bit numbers so that neighbours differ in exactly one bit.
- The i-th Gray code is i XOR (i shifted right by 1).
- Shifting right and XOR-ing flips only the bit where the binary count carries.
- Used in rotary encoders and Karnaugh maps.
Watch it run
Loading animation…