The problem with plain binary
Going from 3 (011) to 4 (100) in ordinary binary flips all three bits at once. In real hardware, those bits never switch at the exact same instant — for a brief moment a fast reader could see an invalid intermediate value like 111 or 000. For a counter driving a physical position sensor (like a rotary encoder), that brief glitch is a real, observable error, not just a theoretical concern.
What makes a code "Gray"
Gray code is an alternative binary encoding where every consecutive value differs from the previous one in exactly one bit. Counting 0 to 7 in Gray code goes 000, 001, 011, 010, 110, 111, 101, 100 — every step changes a single bit, so there is no possible invalid transient value between any two consecutive states.
Converting binary to Gray and back
Binary-to-Gray conversion is a single XOR pass: each Gray bit is the XOR of the corresponding binary bit with the binary bit one position higher (the top bit is copied unchanged).
- G[n] = B[n] (most significant bit, unchanged)
- G[i] = B[i] ⊕ B[i+1] for every other bit
- Converting back just runs the same idea in reverse, accumulating XORs from the top bit down.
Parity bits: detecting single-bit errors
A parity bit is a single extra bit appended to a data word, set so that the total number of 1s (including the parity bit) is always even (even parity) or always odd (odd parity). If exactly one bit flips in transmission or storage — due to noise, a cosmic ray, a loose connection — the parity no longer matches, and the receiving circuit can flag the error.
Parity can detect a single flipped bit reliably, but not two flipped bits at once (two flips cancel out and parity still matches) — which is why more critical systems use stronger error-correcting codes layered on top of this same basic idea.
Where they're used
Gray code shows up in rotary and linear position encoders, in clock-domain-crossing counters, and in Karnaugh map axis ordering (the Karnaugh maps article uses exactly this property). Parity bits protect RAM, serial links, and simple memory buses. Boolflow ships ready-made Binary→Gray, Gray→Binary, and Parity blocks — load a Gray code example and step a binary counter alongside its Gray-coded output to see only one bit change per step.