About Gray Code
Gray code (formally the binary reflected Gray code, BRGC) is an ordering of binary numbers in which adjacent values differ by exactly one bit. Invented by Frank Gray at Bell Labs in 1947 and patented for use in pulse-code modulation, it eliminates the transient multi-bit errors that occur in ordinary binary when multiple bits flip simultaneously — critical in digital electronics where signals cannot change instantaneously. Rotary shaft encoders, analogue-to-digital converters, and Karnaugh maps all exploit the single-bit-change property to reduce glitch errors and simplify logic minimisation.
This simulation visualises Gray codes as a path on an n-dimensional hypercube: each bit position corresponds to one axis, and each Gray code transition is an edge of the cube. You can step through the sequence for n from 1 to 5, watching the traversal visit every vertex exactly once — a Hamiltonian path on the hypercube graph — and observe how each transition flips exactly one bit.
Frequently Asked Questions
How is the standard Gray code constructed from a binary number?
The n-bit Gray code G(k) for integer k is computed as G(k) = k XOR (k >> 1): take k's binary representation, right-shift it by one position, and XOR with the original. For example, k=6 (binary 110) → 110 XOR 011 = 101 (decimal 5), giving the 4th Gray code in a 3-bit sequence (0,1,3,2,6,7,5,4 in decimal). The inverse — recovering k from G(k) — requires an iterative prefix XOR across the bits.
Why does Gray code matter for rotary encoders?
A rotary encoder reads the angular position of a shaft from a pattern of reflective or conductive segments. If standard binary is used, a transition such as 7→8 (0111→1000) requires all four bits to flip; if the mechanical read-out slightly misaligns, intermediate states like 0110 or 1010 may be read, reporting wildly wrong positions. Gray code ensures that adjacent positions always differ by exactly one segment, so only one bit can ever be in an ambiguous state, limiting position errors to ±1.
What is the "reflected" construction that gives Gray code its full name?
The n-bit BRGC is built recursively: take the (n−1)-bit Gray code list, prefix each with 0 to get the first 2n−1 entries, then append the reversed list prefixed with 1. The "reflected" refers to this mirror-image reversal, which ensures the last entry of the 0-prefix half and the first entry of the 1-prefix half differ by exactly one bit (the MSB). The recursion produces the same result as the XOR formula G(k) = k XOR (k >> 1).
How is Gray code used in Karnaugh maps?
Karnaugh maps arrange truth-table cells in Gray code order along each axis so that logically adjacent minterms (differing in one variable) are physically adjacent in the grid. This allows visual identification of rectangles of 1s (or 0s) that correspond to prime implicants, simplifying Boolean expressions. Without Gray ordering, adjacent cells in the grid would not be logically adjacent, defeating the purpose of the map.
Is the Gray code sequence unique?
No. Many different single-bit-change sequences exist for n bits; these are called Gray codes or Hamiltonian cycles on the n-cube, and their number grows super-exponentially with n. The binary reflected Gray code is the canonical choice due to its simple recursive construction and the closed-form XOR formula. Other families include balanced Gray codes (where each bit flips equally often), monotone Gray codes, and Snake-in-the-Box codes used in error correction.
How does Gray code relate to the Tower of Hanoi?
The sequence of bit positions that change in successive Gray code values is exactly the sequence of disk numbers moved in the optimal Tower of Hanoi solution: position 1, 2, 1, 3, 1, 2, 1, 4, … (the ruler sequence). This isomorphism means that each move in the Hanoi puzzle corresponds to flipping one bit in the Gray code counter, providing a deep combinatorial connection between the two problems.
What is a balanced Gray code?
A balanced Gray code is one where each bit position changes as nearly equally often as possible across the 2n transitions. In the standard BRGC, the MSB flips only once while the LSB flips 2n−1 times, creating a very unequal distribution. Balanced Gray codes distribute transitions evenly, which is important in applications like wear-levelling of flash memory and reducing switching power in CMOS circuits.
How is Gray code used in error correction?
Snake-in-the-Box codes are Gray code paths on the n-cube where no two non-adjacent path nodes are also adjacent in the cube (a "snaking" Hamiltonian path). They form self-detecting single-error codes: any single bit error in a codeword moves to a non-codeword node. Coil-in-the-Box codes achieve larger minimum Hamming distance. These combinatorial codes appear in fault-tolerant computing and data storage systems.
Can Gray codes be defined for non-binary number systems?
Yes. Balanced ternary Gray codes, mixed-radix Gray codes, and Gray codes for permutations all exist. The Steinhaus–Johnson–Trotter algorithm generates all permutations of N elements by adjacent transpositions, which is the permutation analogue of a single-bit-change Gray code. These are used in exhaustive search algorithms that enumerate permutations or combinations with minimal change between successive states.
How does Gray code simplify digital circuit design?
In sequential state machines (FSMs), encoding states in Gray code ensures that state transitions require only one flip-flop to change at a time. This eliminates transient glitch states that might trigger unintended logic, reducing power consumption and improving timing margins. FPGA design tools often automatically offer Gray-code FSM encoding as an option when the designer selects "safe" or "one-hot-adjacent" encoding styles.