Gray Code Changes One Bit, but a Stable Error Can Still Be Legal
Changing one bit between neighboring positions is useful. It does not make a stable three-bit word trustworthy: every possible three-bit word already names a legal position.
A Gray code orders binary words so neighboring entries differ in one bit. A bit is a binary digit, either 0 or 1; a word is a fixed-width group of bits. We will draw a three-bit paper ring, encode and decode all eight positions, then deliberately flip one bit while the true position stays fixed. The received word remains legal.
This is an unpowered paper-and-computer experiment. The ring is original constructed geometry, not a manufactured encoder. The model has no sensor, electrical connection, contact bounce, propagation delay or sampling-time measurement. It cannot establish what a real position sensor would report.
Prepare the paper and complete reader
Use paper, a pencil, a ruler and a computer with CPython 3.9 or later. CPython is the reference implementation of Python; this lesson's actual host checks used version 3.9.6. A compass or a printed copy of the ring helps with the drawing, but no powered apparatus is required.
Extract the reader ZIP archive, a compressed collection of files, into a normal folder. Open reader.html or README.txt there. Comma-separated values (CSV) files store the constructed tables and blank worksheet. Scalable Vector Graphics (SVG) files are editable drawings; Portable Network Graphics (PNG) files are full-size images. Preserve the supplied case-sensitive filenames and folders.
Declare the order before reading a track
Our position index n is an integer from 0 through 7. The three Gray bits are written g₂g₁g₀, left to right. The leftmost is the most-significant bit (MSB) in our ordering convention; it is the outer track. The middle and inner tracks are g₁ and g₀. A radial track lies at one chosen distance from the center. Read all three at the same sector center. Dark means 1 and pale means 0.
Split the paper ring into eight equal sectors: 360 degrees / 8 = 45 degrees per sector. Index 0 is at the top; indices increase clockwise. These angles only lay out the paper. They are not an actual sensor's resolution or an accuracy specification. The last index 7 and the first index 0 are also neighbors: that return is the wrap.

Encode an index and undo the encoding
The specific code here is the binary-reflected Gray code. One way to build a wider ordered list is to prefix 0 to the previous list, then prefix 1 to a reversed copy of it. The reversal explains “reflected.” For the ordinary binary representation of n, the same result is
G(n) = n XOR (n shifted right by one bit).
Exclusive OR (XOR) produces 1 when its two input bits differ and 0 when they match. A right shift moves each binary bit one place toward the right, discards the last bit and supplies a zero on the left here. In the Python expression n ^ (n >> 1), ^ means bitwise XOR and >> means right shift. At n = 2, ordinary binary 010 shifted right is 001; 010 XOR 001 gives Gray word 011.
| Index n | Ordinary binary | Gray g₂g₁g₀ | Bits changed to next Gray index |
|---|---|---|---|
| 0 | 000 | 000 | 1 |
| 1 | 001 | 001 | 1 |
| 2 | 010 | 011 | 1 |
| 3 | 011 | 010 | 1 |
| 4 | 100 | 110 | 1 |
| 5 | 101 | 111 | 1 |
| 6 | 110 | 101 | 1 |
| 7 | 111 | 100 | 1 (wrap to 0) |
Do not interpret a Gray word as an ordinary binary numeral. For inverse decoding, let ordinary binary bits be b₂b₁b₀. Start with b₂ = g₂, then compute b₁ = b₂ XOR g₁ and b₀ = b₁ XOR g₀. For Gray 111 the binary result is 101, so the decoded index is 5, not 7. The code applies this running XOR from left to right for any supported width.
Encoding and inverse decoding map the eight indices one to one onto all eight three-bit words. There are no unused words. That is the central error-detection limit, independent of how neatly adjacent sectors change.
A legal word can be a stable error
The Hamming distance between two equal-length bit words counts the bit positions where they differ. Every neighboring pair in our ordered ring, including 100 → 000 at the wrap, has distance 1. But not every distance-1 pair is a neighboring pair of position indices.
A graph represents relationships with vertices and edges. In the next figure, each circle is one legal word and its decoded index. Blue edges join successive ring indices. All twelve undirected distance-1 edges are shown; the four additional connections include the highlighted error. A crossing of lines without a circle is not another vertex.

Hold the true paper position at n = 2. Its correct word is 011. Flip only the leftmost bit to receive 111. Inverse decoding returns 5. If 111 stays unchanged at two sample times, the model correctly reports equal observed words. It cannot discover the hidden truth “the paper stayed at 2” from those words alone. We know the error because we constructed it with a separately declared true position, not because the decoder detected it.
There are 8 × 3 = 24 directed one-bit flips. Each flip lands on a different legal word. The graph has twelve undirected edges because each can be traversed in two directions; these are two ways of counting the same relationships, not two conflicting datasets. Some flips imitate a valid neighboring step. Adjacency therefore supplies no general error correction, and even an adjacency check cannot detect every stable one-bit error.
A skipped observation is an unknown interval
Suppose the recorded words are 000 at sample index 0 and 011 at sample index 2. They decode to indices 0 and 2 and differ in two bits. Ordinary motion through 0 → 1 → 2 with word 001 unrecorded is one possible explanation. The endpoints alone also allow other paths or corrupted words. A skipped word does not uniquely prove a fault or a direction.
A sample index orders our worksheet rows; it is not a timestamp or a speed limit. Even successive sample indices do not prove the paper moved only one sector between them. This model labels relations between decoded endpoints, such as “next code index”; it never turns that label into an actual direction claim. Additional, independently justified assumptions would be needed for a motion or fault decision.
An explicitly unknown word remains unknown. The blank worksheet uses empty word cells, sample_state=unknown and provenance=blank. Known word 000 is a valid zero position, so it cannot serve as the missing-data marker. The program rejects an unknown row containing 000 instead of quietly converting the empty cell to zero.
Controls, faults and restoration
- Write the eight index/word pairs from the first table. Read each adjacent pair and the wrap. Mark which one bit changes. Check the complete constructed adjacent sequence with the supplied program.
- Use the known-error control: declare the true position fixed at 2, copy its correct word 011, then deliberately change g₂ to 1. Decode 111 manually to 5. The stable-error records deliberately contain 111 twice; their true held index 2 is this experimental instruction, not an inferred field.
- Restore the correct word 011 and decode it back to 2. This restoration checks the inversion arithmetic; it does not test a physical sensor's recovery.
- Analyze the skipped/unknown sequence. Confirm that the gap between sample indices 0 and 2 is reported as one unrecorded sample index, and that a comparison with an unknown endpoint has no Hamming-distance value.
- Copy the blank worksheet before entering your own work. Keep blank cells unknown. For a known entry set the state to
known, enter exactly three binary digits and change provenance toreader_observation. Record separately whether it was a hand calculation, software result or actual observation; this flag alone certifies none of them. - Try a deliberately malformed copy with a duplicate record identifier or
word=00x. Confirm that the program exits with an error. Restore the valid file before continuing; do not hide the rejected row or relabel it as a measurement.
Run the complete model
The complete Python model follows. Widths are bounded to integers 1 through 8, words to that exact binary width, sample sequences to 1 through 128 rows, indices to 0 through 1,000,000 and CSV text to 100,000 characters. Boolean values are rejected where integer arguments are required. Record identifiers and indices must be unique, and indices must strictly increase. CSV columns have one exact order; extra, missing and malformed fields fail. Empty rows are rejected rather than silently dropped as if no sample existed. These are file/model limits, not encoder operating limits.
"""Reflected Gray words for a paper/model experiment, Python 3.9+.
Words are most-significant bit first. Width is 1..8; a sample sequence
has 1..128 records. Unknown samples stay None, never an invented zero.
Endpoint relations establish neither actual motion nor error correction.
"""
import argparse
import csv
import io
import json
from pathlib import Path
import re
MAX_WIDTH = 8
MAX_RECORDS = 128
MAX_INDEX = 1000000
MAX_TEXT = 100000
FIELDS = ['record_id', 'sample_index', 'word', 'sample_state', 'provenance']
def width_checked(width):
if type(width) is not int or not 1 <= width <= MAX_WIDTH:
raise ValueError('width must be an integer from 1 through 8')
return width
def encode(position, width=3):
width_checked(width)
if type(position) is not int or not 0 <= position < (1 << width):
raise ValueError('position must be an integer within this code ring')
return format(position ^ (position >> 1), '0' + str(width) + 'b')
def word_checked(word, width):
width_checked(width)
if type(word) is not str or len(word) != width or any(c not in '01' for c in word):
raise ValueError('word must contain exactly width binary digits, MSB first')
return word
def decode(word, width=3):
word_checked(word, width)
binary_bit, position = 0, 0
for digit in word:
binary_bit ^= int(digit)
position = (position << 1) | binary_bit
return position
def hamming(first, second, width=3):
word_checked(first, width)
word_checked(second, width)
return sum(a != b for a, b in zip(first, second))
def one_bit_errors(width=3):
"""Construct every stable one-bit corruption; no hardware fault is inferred."""
width_checked(width)
output = []
for n in range(1 << width):
sent = encode(n, width)
for bit_index in range(width):
changed = list(sent)
changed[bit_index] = '1' if changed[bit_index] == '0' else '0'
received = ''.join(changed)
output.append(dict(true_position=n, sent_word=sent,
bit_index_from_left=bit_index, received_word=received,
decoded_position=decode(received, width), provenance='constructed'))
return output
def validated_samples(records, width):
width_checked(width)
if type(records) is not list or not 1 <= len(records) <= MAX_RECORDS:
raise ValueError('sequence must contain 1 through 128 records')
ids, indices, output = set(), set(), []
previous_index = -1
for r in records:
if type(r) is not dict or set(r) != set(FIELDS):
raise ValueError('each sample must have the exact five fields')
rid, index = r['record_id'], r['sample_index']
if type(rid) is not str or re.fullmatch(r'[A-Za-z0-9_-]{1,32}', rid) is None:
raise ValueError('record_id must be 1..32 letters, digits, hyphens or underscores')
if rid in ids:
raise ValueError('duplicate record_id')
if type(index) is not int or not 0 <= index <= MAX_INDEX:
raise ValueError('sample_index must be an integer from 0 through 1000000')
if index in indices or index <= previous_index:
raise ValueError('sample indices must be unique and strictly increasing')
state, provenance, word = r['sample_state'], r['provenance'], r['word']
if provenance not in ('blank', 'constructed', 'reader_observation'):
raise ValueError('unknown provenance')
if state not in ('known', 'unknown'):
raise ValueError('sample_state must be known or unknown')
if state == 'unknown':
if word is not None:
raise ValueError('unknown sample must have no word')
decoded = None
else:
if provenance == 'blank':
raise ValueError('blank worksheet may not claim a known sample')
decoded = decode(word, width)
ids.add(rid)
indices.add(index)
previous_index = index
output.append(dict(r, decoded_position=decoded))
return output
def parse_records(text, width=3):
width_checked(width)
if type(text) is not str or not text or len(text) > MAX_TEXT:
raise ValueError('CSV text must contain 1..100000 characters')
if any(not line.strip() for line in text.splitlines()):
raise ValueError('empty CSV rows are not unknown samples')
try:
reader = csv.DictReader(io.StringIO(text), strict=True)
if reader.fieldnames != FIELDS:
raise ValueError('unexpected CSV columns or column order')
rows = []
for raw in reader:
if None in raw or any(v is None for v in raw.values()):
raise ValueError('malformed CSV row')
index = raw['sample_index']
if re.fullmatch(r'0|[1-9][0-9]*', index) is None:
raise ValueError('sample_index must use unsigned decimal integer notation')
rows.append(dict(raw, sample_index=int(index),
word=None if raw['word'] == '' else raw['word']))
if len(rows) > MAX_RECORDS:
raise ValueError('sequence must contain 1 through 128 records')
except csv.Error as exc:
raise ValueError('malformed CSV: ' + str(exc)) from exc
validated_samples(rows, width)
return rows
def analyse_sequence(records, width=3):
samples = validated_samples(records, width)
transitions, count = [], 1 << width
for first, second in zip(samples, samples[1:]):
missed = second['sample_index'] - first['sample_index'] - 1
known = first['word'] is not None and second['word'] is not None
relation, changed = 'unknown', None
if known:
changed = hamming(first['word'], second['word'], width)
delta = (second['decoded_position'] - first['decoded_position']) % count
if delta == 0:
relation = 'same_word'
elif delta == 1:
relation = 'next_code_index'
elif delta == count - 1:
relation = 'previous_code_index'
else:
relation = 'other_code_indices'
interval = 'unknown_endpoint' if not known else (
'unrecorded_samples' if missed else 'consecutive_sample_indices')
transitions.append(dict(from_id=first['record_id'], to_id=second['record_id'],
unrecorded_sample_indices=missed, interval_status=interval,
endpoint_relation=relation, bit_changes=changed))
return dict(width=width, samples=samples, transitions=transitions,
physical_direction_inferred=False, fault_proven=False,
error_correction_claimed=False,
scope='Only sampled code words and endpoint relations; no speed bound, true path or fault model assumed.')
def demo(width=3):
width_checked(width)
legal = [dict(position=n, word=encode(n, width),
next_position=(n + 1) % (1 << width),
next_bit_changes=hamming(encode(n, width),
encode((n + 1) % (1 << width), width), width))
for n in range(1 << width)]
return dict(width=width, legal_positions=legal, one_bit_errors=one_bit_errors(width),
all_words_used=True, physical_tested=False,
scope='Constructed complete reflected Gray mapping, not an encoder or electrical simulation.')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--width', type=int, default=3)
parser.add_argument('--records', type=Path)
args = parser.parse_args()
try:
width_checked(args.width)
if args.records:
if args.records.stat().st_size > MAX_TEXT:
raise ValueError('record file exceeds 100000 bytes')
result = analyse_sequence(parse_records(args.records.read_text(encoding='utf-8'),
args.width), args.width)
else:
result = demo(args.width)
except (ValueError, OSError, UnicodeError) as exc:
parser.error(str(exc))
print(json.dumps(result, indent=2, allow_nan=False))
if __name__ == '__main__':
main()
From the extracted folder, run the actual commands below. A command-line interface is the text-based way to pass options to a program. No driver, microcontroller connection or external Python library is required.
python3 -B -m unittest discover -v
python3 -B gray_lab.py --width 3
python3 -B gray_lab.py --records data/constructed-adjacent.csv
python3 -B gray_lab.py --records data/constructed-stable-error.csv
python3 -B gray_lab.py --records data/constructed-skips.csv
python3 -B gray_lab.py --records data/blank-observations.csv
The default output lists the eight legal positions and 24 directed one-bit cases. The stable-error file decodes both words as 5 and labels the endpoints same_word. The skip example retains one unrecorded sample index; comparisons involving its empty word have bit_changes: null. In JSON, JavaScript Object Notation, null represents an absent value here. It does not mean zero. The blank file returns three unknown decoded positions.
The complete test source checks all supported-width round trips and wrap adjacencies, all 24 three-bit flips, exact selected errors, unknowns, gaps, bounds, malformed records and the actual command-line paths. The author executed 25 host tests and all documented commands. Actual host output is included. This is software verification of the delivered model, not firmware compilation, target execution or a physical encoder test.
What this experiment deliberately does not promise
In a physical Gray-pattern encoder, an ideal boundary between neighboring codes changes one track. That statement does not guarantee valid electrical thresholds, simultaneous sampling, settling, alignment, noise immunity or direction. None of those mechanisms is modeled here. A code pattern, an actual sensor and the logic that interprets its samples are separate things.
Extra independent information can enable specific fault checks; it must come with an explicit model and assumptions. This three-bit mapping has no spare words or added check bits, so it supplies no such redundancy by itself. Do not call a stable legal word “verified position,” or call an unexpected endpoint “proved hardware fault,” from this exercise alone.
Challenge: can an error imitate one reverse step?
The true index remains 2, whose correct word is 011. Flip only the middle bit g₁. Which index does the received word name, and would a neighboring-index check necessarily reject it?
Worked answer
The new word is 001. Running XOR decodes it to binary 001, index 1. It looks like one reverse step in the declared index order, so a check that merely accepts neighboring indices would not reject it. The hidden true index stayed 2. Restore the middle bit to recover 011; additional knowledge, not adjacency alone, identified the fault.
Primary sources and related lessons
The National Institute of Standards and Technology (NIST) Gray-code entry defines one-bit changes between consecutive entries. Frank Gray's original Pulse Code Communication, United States Patent 2,632,058, issued March 17, 1953, describes reflected binary ordering and translation back to conventional binary. Our formula implementation, paper geometry, error graph, datasets and limits are original. See the source index and checked scope; no vendor manual or patent figure is redistributed.
Compare a changing word with the separate rising-edge storage lesson, and compare an accepted code word with the explicitly timed input rules in the up/down-counter protocol lesson. Their actual hardware rules are not imported into this unpowered paper model.