Skip to content
StackDecode
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

  1. A Gray code lists all n-bit numbers so that neighbours differ in exactly one bit.
  2. The i-th Gray code is i XOR (i shifted right by 1).
  3. Shifting right and XOR-ing flips only the bit where the binary count carries.
  4. Used in rotary encoders and Karnaugh maps.

Watch it run

Loading animation…