Gray code in one minute
Gray code (reflected binary code) is a binary numbering system in which any two consecutive numbers differ in exactly one bit. That single-bit-change property is what makes it valuable for rotary encoders, Karnaugh maps, and digital communications where a transient misread should never cause a large jump in the decoded value.
How it works
To convert a binary number to Gray code, XOR the number with itself shifted one position to the right:
gray = n ^ (n >> 1)
The most significant bit is always copied unchanged; every other Gray bit is the XOR of the current binary bit and the bit immediately to its left.
Decoding reverses the process by accumulating XORs from the top bit down:
binary[0] = gray[0]
binary[i] = binary[i-1] ^ gray[i]
This converter applies these exact operations, so the encoded and decoded results are always bit-accurate for any non-negative integer within the safe integer range.
Example and tips
Decimal 4 is 100 in binary. Its Gray code is 100 ^ 010 = 110, which is
decimal 6 when read as plain binary. Notice that the value 4 and its
neighbour 5 (Gray 111) differ in only one bit — exactly the guarantee Gray
code provides. When entering binary strings, leading zeros are preserved in the
display so you can line up the bit columns for teaching or debugging.
Gray code conversion table (0–15)
| Decimal | Binary | Gray code |
|---|---|---|
| 0 | 0000 | 0000 |
| 1 | 0001 | 0001 |
| 2 | 0010 | 0011 |
| 3 | 0011 | 0010 |
| 4 | 0100 | 0110 |
| 5 | 0101 | 0111 |
| 6 | 0110 | 0101 |
| 7 | 0111 | 0100 |
| 8 | 1000 | 1100 |
| 9 | 1001 | 1101 |
| 10 | 1010 | 1111 |
| 11 | 1011 | 1110 |
| 12 | 1100 | 1010 |
| 13 | 1101 | 1011 |
| 14 | 1110 | 1001 |
| 15 | 1111 | 1000 |
Notice that adjacent rows always differ in exactly one bit position — that is the defining property of reflected binary Gray code.
Real-world applications
Rotary encoders. An absolute rotary encoder reads the angular position of a shaft using optical or magnetic sensors at fixed bit positions. If the shaft is between two position marks during a read, multiple bits might change simultaneously in standard binary, producing a transient reading far from either position. Gray code eliminates this: only one bit changes at any boundary, so the worst-case error is exactly one position step.
Karnaugh maps. In digital logic design, Karnaugh maps use Gray code ordering for their row and column labels so that adjacent cells differ in only one variable. This makes it easy to spot groupings of adjacent cells (implicants) that can be combined to simplify a Boolean expression.
Genetic algorithms and error correction. Some implementations of genetic algorithms encode numerical variables in Gray code to reduce the Hamming distance between adjacent values, which helps mutation operators make smaller incremental steps. It is also used in some error-correcting code designs where single-bit flip detection is important.