Gray code is a binary ordering in which two consecutive values differ by exactly one bit. That single-change rule makes Gray code useful whenever several electrical signals cannot be guaranteed to switch at precisely the same instant. A conventional binary counter may cross a boundary by changing multiple bits; a sensor that samples during that transition can briefly observe a value that was never intended. Gray code limits the ambiguity to one changing channel.
This guide develops the binary reflected sequence, shows how to convert in both directions, and explains where the one-bit property helps in real hardware. It treats Gray code as a representation and sequencing technique, not as a replacement for ordinary binary arithmetic.
How Gray Code Differs from Ordinary Binary
Ordinary binary is a positional number system. Each bit has a power-of-two weight, so arithmetic and comparisons work directly on the stored pattern. Gray code assigns patterns in a deliberately rearranged order. The pattern still identifies a position or state, but its bits do not carry independent positional weights.
The difference is clear around decimal 3 and 4:
| Decimal | Ordinary binary | Gray code | Bits changed from prior row |
|---|---|---|---|
| 0 | 000 | 000 | - |
| 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 |
The ordinary transition from 011 to 100 changes all three bits. If those lines have different propagation delays, intermediate observations such as 000 or 110 are possible. The corresponding Gray code transition is 010 to 110, so only the most significant channel changes.
For a refresher on weighted base-2 notation, see the binary number system guide. The binary table is also useful when comparing decimal values with ordinary binary patterns.
The Binary Reflected Gray Code Sequence
The most common form is binary reflected Gray code. “Reflected” describes a recursive construction: copy the existing list in reverse order, prefix the original half with zero, and prefix the reflected half with one.
Start with the one-bit list:
0
1To make two bits, reflect the list and add prefixes:
Original with 0: 00, 01
Reflected with 1: 11, 10
Result: 00, 01, 11, 10Repeat the procedure for three bits:
Original with 0: 000, 001, 011, 010
Reflected with 1: 110, 111, 101, 100This construction preserves the one-bit transition inside each half. At the join, the two middle patterns differ only in their new prefix. A reflected Gray code is also cyclic: the final pattern and the first pattern differ by one bit, which is especially valuable for a rotating encoder that wraps from its highest position back to zero.
An n-bit Gray code sequence contains 2^n unique patterns. It visits every possible pattern once, but the visit order is not ordinary numeric order.
Convert Binary to Gray Code
The direct conversion uses an exclusive OR operation. Keep the most significant binary bit unchanged. Every following Gray code bit is the XOR of two adjacent binary bits:
gray[most significant] = binary[most significant]
gray[i] = binary[i + 1] XOR binary[i]Another compact expression is:
gray = binary XOR (binary shifted right by one position)Worked Example: Binary 1011
Convert 1011 one position at a time:
| Position | Calculation | Result |
|---|---|---|
| First | Keep 1 | 1 |
| Second | 1 XOR 0 | 1 |
| Third | 0 XOR 1 | 1 |
| Fourth | 1 XOR 1 | 0 |
Therefore binary 1011 becomes Gray code 1110. The decimal value is 11, but that meaning comes from the original binary index, not from treating 1110 as a positional Gray number.
XOR outputs one when its inputs differ. The logic gates guide covers XOR truth tables and the gates that implement this conversion in digital circuits.
Convert Gray Code Back to Binary
Reverse conversion uses a running XOR rather than independent adjacent pairs:
- Copy the most significant Gray code bit to the binary result.
- XOR that binary result bit with the next Gray bit.
- Use each newly recovered binary bit in the following XOR.
- Continue to the least significant position.
Worked Example: Gray 1110
| Position | Calculation | Binary result |
|---|---|---|
| First | Copy 1 | 1 |
| Second | 1 XOR 1 | 0 |
| Third | 0 XOR 1 | 1 |
| Fourth | 1 XOR 0 | 1 |
The recovered binary pattern is 1011. You can then enter that ordinary pattern in the binary to decimal converter to obtain 11. Keeping these two stages separate prevents a common error: a Gray code word must be decoded before it can be evaluated with positional weights.
Why Rotary Encoders Use Gray Code
An absolute rotary encoder can place several concentric tracks around a disk. Each track is read by a sensor and contributes one channel to the position word. With ordinary binary markings, a boundary such as 7 to 8 could require every track to change. Mechanical alignment, track tolerances, dust, and sensor thresholds make perfectly simultaneous switching unrealistic.
With Gray code markings, adjacent angular sectors differ on one track. Near a boundary, all stable tracks still agree and only one sensor is uncertain. The observed result is therefore one of the two neighboring positions rather than an unrelated distant position. Gray code does not remove noise or make a sensor infallible, but it reduces transition ambiguity substantially.
The same logic applies to linear position encoders. The code sequence is laid along a rail instead of around a disk, while adjacent physical regions retain the one-change property.
Other Gray Code Applications
Asynchronous Clock-Domain Crossing
Hardware often needs to pass a counter between unrelated clock domains. Sampling a multi-bit binary counter while it changes can capture bits from different counter states. Designers commonly convert the counter to Gray code before synchronization because only one source bit changes per increment. The receiving side still needs proper synchronizer circuitry; Gray code reduces incoherent multi-bit combinations but does not solve metastability by itself.
Karnaugh Maps
Rows and columns in a Karnaugh map use Gray code order so adjacent cells differ in one Boolean variable. That arrangement makes groups of neighboring cells correspond to simplified logical terms. The connection is structural: Gray code places one-variable changes next to one another, while Boolean algebra supplies the simplification rules.
State Machines and Search Spaces
Some state assignments use Gray code to reduce simultaneous switching and dynamic power. Algorithms may also traverse bit patterns in this order when they want consecutive candidates to differ by one decision. Whether that is beneficial depends on the cost function and the hardware; the sequence should not be adopted automatically.
Practical Implementation Notes
For an unsigned integer b, many programming languages can compute the reflected form with b ^ (b >> 1). Decoding requires repeatedly XORing the shifted value or propagating the recovered most significant bit toward the right.
encode(b):
return b XOR (b shifted right by 1)
decode(g):
b = 0
while g is not zero:
b = b XOR g
g = g shifted right by 1
return bDefine a fixed width when serializing the result. Leading zeros distinguish a four-channel encoder word from an unbounded integer display. Also specify whether the system uses the standard reflected Gray code or another single-change code; not every ordered code with a unit Hamming distance has the same numeric mapping.
Common Mistakes
- Reading the pattern as weighted binary. Decode Gray code first, then calculate the ordinary binary value.
- Assuming every pair of values differs by one bit. The promise applies to adjacent positions in the defined sequence, not arbitrary values.
- Ignoring width. Dropping leading zeros can hide the physical channel count and break fixed-width interfaces.
- Using it as error-correcting code. Gray code reduces transition ambiguity, but it does not add redundant bits that locate and repair corruption.
- Skipping synchronization. A clock-domain counter still needs a correct crossing design even when its exported count uses Gray code.
- Confusing bit order with byte order. The sequence says which bit changes; it does not define how multi-byte data is laid out in memory.
Frequently Asked Questions
What is Gray code in simple terms?
Gray code is an ordering of bit patterns where each neighboring pattern changes in exactly one position. It is useful for representing a changing physical state because small timing differences cannot create a mixture of several changing bits.
Why is it called reflected Gray code?
The standard sequence is built by reflecting the current list, adding a zero prefix to the original half, and adding a one prefix to the reversed half. Repeating that procedure creates any required bit width.
Is Gray code a binary number system?
It uses binary symbols, but its positions do not have independent power-of-two weights. Treat it as an ordered mapping of states. Convert the pattern to ordinary binary before doing arithmetic.
Can Gray code detect or correct errors?
Not by itself. The one-change arrangement can make implausible transitions easier to notice in a constrained motion system, but it has no general redundancy for correction. Error-correcting designs use techniques such as Hamming code.
How many values can an n-bit sequence represent?
An n-bit reflected sequence contains 2^n unique words, the same count as ordinary binary. Four channels provide 16 states, while ten channels provide 1024 states.
Does Gray code always wrap safely?
The standard reflected sequence is cyclic, so its last and first words also differ by one bit. A custom subset may lose that property; verify the actual endpoints before using it in a rotating device.
Summary
Gray code rearranges binary patterns so every step changes one bit. The reflected construction scales recursively, binary conversion uses adjacent XOR, and reverse conversion uses cumulative XOR. Its strongest applications are position sensing, controlled clock-domain counters, Karnaugh maps, and state sequences where simultaneous transitions create risk. Use Gray code for representation at boundaries, then decode to ordinary binary for arithmetic and numerical comparison.
