Gray Code
Gray code orders binary values so consecutive numbers differ in exactly one bit, avoiding transient errors when a value changes.
One Bit at a Time
In ordinary binary, incrementing a number can flip many bits at once; going from 0111 to 1000 changes all four. If those bits do not switch at exactly the same instant, a circuit sampling the value mid-change can momentarily read a wrong number. Gray code is an ordering of binary values in which each successive value differs from the previous by exactly one bit, removing this hazard.
| dec | binary | gray |
|---|---|---|
| 0 | 000 | 000 |
| 1 | 001 | 001 |
| 2 | 010 | 011 |
| 3 | 011 | 010 |
| 4 | 100 | 110 |
Converting To and From
The reflected binary Gray code has a compact conversion. To turn a binary number into Gray code, XOR it with itself shifted right by one bit: gray = binary XOR (binary >> 1). The reverse is a running XOR from the most significant bit down. Both conversions are cheap combinational logic.
def bin_to_gray(n):
return n ^ (n >> 1)
def gray_to_bin(g):
b = 0
while g:
b ^= g
g >>= 1
return b
Why It Matters in Hardware
Gray code is the standard encoding for pointers in an asynchronous FIFO that crosses clock domains. Because only one bit changes per step, a pointer sampled by the other clock domain mid-transition resolves to either the old or the new value, never a corrupted intermediate, which is essential for safe clock-domain crossing. It is also used in rotary and linear position encoders, where a single-bit-change guarantee prevents large false readings at boundaries between positions.
Beyond Position Sensing
Gray codes appear in Karnaugh maps, where adjacent cells differ by one variable, making groupings of simplifiable terms visible. They also arise in error-tolerant communication and in some analog-to-digital converter designs. Wherever a value transitions frequently and might be observed mid-change, a single-bit-change encoding turns a potential glitch into a harmless ambiguity.