Gray Code Converter
Convert between binary and reflected Gray code, both ways.
Decimal value: 7.
Bit-by-bit — highlighted bits differ between the two codes
Gray code is a binary ordering in which any two consecutive values differ by exactly one bit. To convert binary to Gray code, XOR each bit with the bit to its left: gray = B ⊕ (B >> 1). For example, binary 0101 (decimal 5) becomes Gray code 0111, whose decimal value is 7.
What Gray code is
Reflected Gray code, named after physicist Frank Gray, is an alternative way to order binary numbers so that stepping from one value to the next flips only a single bit. Ordinary binary counting can flip several bits at once — going from 3 (011) to 4 (100) changes all three low bits — which risks transient glitches when the bits do not update at exactly the same instant. Gray code sidesteps that by guaranteeing a one-bit change between every adjacent pair, which is why it is favored in hardware that reads a value while it is still moving.
Each Gray bit is the binary bit XORed with the binary bit to its left; the most significant bit is copied unchanged.
Worked example: binary 0101
Take the binary value 0101 (decimal 5) and turn it into Gray code by XORing it with a copy of itself shifted one place to the right.
- 1 Write the binary value. B = 0101, which is decimal 5.
- 2 Shift a copy right by one place. B >> 1 = 0010, dropping the last bit and adding a leading 0.
- 3 XOR the two rows column by column. 0101 ⊕ 0010: a column is 1 only where the bits differ, giving 0, 1, 1, 1.
- 4 Read the Gray code. The result is 0111, whose decimal value is 7. The most significant bit is unchanged because it XORs with an implicit 0.
Binary and Gray code, 0 to 7
Each Gray code differs from the one above it in exactly one bit position.
| Decimal | Binary | Gray code | Bit changed vs previous |
|---|---|---|---|
| 0 | 000 | 000 | — |
| 1 | 001 | 001 | bit 0 |
| 2 | 010 | 011 | bit 1 |
| 3 | 011 | 010 | bit 0 |
| 4 | 100 | 110 | bit 2 |
| 5 | 101 | 111 | bit 0 |
| 6 | 110 | 101 | bit 1 |
| 7 | 111 | 100 | bit 0 |
Where Gray code is used, and why it reflects
Because only one bit changes between adjacent values, Gray code is the standard encoding for rotary and linear position encoders, where a sensor reads a shaft angle that may fall on a boundary between two counts. With plain binary a boundary read could momentarily return a wildly wrong number as several bits settle; with Gray code the worst case is being off by one. The same one-bit property minimizes errors in Karnaugh maps and reduces switching activity in some digital circuits. The name reflected comes from how the sequence is built: to extend an n-bit table to n+1 bits, mirror the existing list, prefix 0 to the original half and 1 to the reflected half — the mirror symmetry is what preserves the single-bit-change rule across the join.