🔢 Gray Code
Reflected binary & hypercube path
000 → 000
Step 0 / 8
View
Bits
Animation
Controls
Stats
Codes (2^n)
8
Changed bit
Binary
000
Gray
000
Info & Theory

Gray code (reflected binary code) orders the 2ⁿ binary values so that any two consecutive codes differ in exactly one bit. It was patented by Frank Gray in 1953.

XOR formula

The Gray code of integer b is g = b XOR (b >> 1). To invert, fold the shifts back: b = g XOR (g>>1) XOR …

Reflect-and-prefix construction

Start with the 1-bit list [0, 1]. To go from n to n+1 bits: take the list, write its reflection (reversed copy) below it, prefix every code in the top half with 0 and every code in the bottom half with 1. The single-bit-change property is preserved at the mirror seam.

Hamiltonian path on the n-cube

Treat each code as a vertex of the n-dimensional hypercube; edges join codes that differ in one bit. A Gray-code sequence is exactly a Hamiltonian path — it visits every vertex once, stepping along one edge at a time.

Applications

  • Rotary / position encoders — one bit changes per step, so a misaligned reading can be off by at most one position instead of a wild multi-bit glitch.
  • Karnaugh maps — rows and columns are Gray-ordered so adjacent cells differ in one variable.
  • Genetic algorithms & error reduction — small value changes map to small bit changes.

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.

About this simulation

Written by MySimulator Team · Reviewed by MySimulator Editorial Review

Last updated: 5 July 2026

This simulation builds the reflected binary Gray code for a chosen number of bits and animates it as a walk across the n-dimensional hypercube. Each integer is converted with g = b XOR (b >> 1), so consecutive codes always differ in one bit. The walk is a Hamiltonian path; a second view maps it onto a rotary encoder disk, a third as a table.

🔬 What it shows

Hypercube view draws the n-cube's vertices and edges, tracing the Hamiltonian path with a green trail and marking the current code. Encoder view shades concentric rings like a real rotary encoder disk. Table view lists every index with binary and Gray values, highlighting the flipped bit.

🎮 How to use

Switch views with the Hypercube, Encoder and Table buttons. The n bits slider (2–6) sets how many bits, and so 2ⁿ codes, appear. Speed (0.2–4) sets how fast Play advances; Step moves one code at a time; Reset returns to code 000.

💡 Did you know?

Frank Gray filed the patent behind this code in 1947 at Bell Labs, working on pulse-code modulation; it was granted in 1953, decades before it became standard in rotary encoders and Karnaugh maps.

Frequently asked questions

What do the three view modes (Hypercube, Encoder, Table) actually show?

Hypercube view draws the cube's vertices and edges and traces the Hamiltonian path as the sequence advances. Encoder view renders the same codes as concentric rings on a disk, like a physical rotary encoder. Table view lists binary and Gray codes side by side.

What does the "changed bit" statistic mean?

It reports which bit position flipped between the previous and current Gray code, counted from the most significant bit. It shows a dash before the first step, then an index such as #0 or #1 — always exactly one bit.

Why does the hypercube layout change when the n bits slider moves?

Each bit adds an axis: 2 bits form a square, 3 bits a cube, and up to 4 bits are flattened using a fixed direction per bit. Above 4 bits the layout switches to a circle, spacing all 2ⁿ codes evenly since a flat projection becomes unreadable.

What are the concentric rings in Encoder view?

Each ring represents one bit, with the outermost ring the most significant. A segment lights up whenever that bit is 1 for the code at that angle, so the disk reproduces the pattern a real absolute rotary encoder prints on its code wheel.

How do the Play, Step and Reset controls differ?

Play animates continuously at the rate set by Speed, advancing one edge at a time until the final code. Step advances exactly one code and stops. Reset returns the sequence to index 0 and stops any running animation.