Gray Code Converter
Convert binary to Gray code, or Gray code back to binary. This Gray code converter shows the XOR behind every bit: 0111 in binary is 0100 in Gray code.
Gray code
Gray code
How to convert binary to Gray code
- 01
Keep the first bit
The leftmost Gray bit is the same as the leftmost binary bit.
- 02
XOR each pair
Every other Gray bit is the XOR of a binary bit and the bit to its left: 1 if they differ, 0 if they match.
- 03
Read the result
For
0111: 0, then 0 ⊕ 1 = 1, 1 ⊕ 1 = 0 and 1 ⊕ 1 = 0, so the Gray code is0100.
How to convert Gray code to binary
Keep the first bit, then XOR each Gray bit with the binary bit you just wrote. For 0100: 0, then 0 ⊕ 1 = 1, 1 ⊕ 0 = 1 and 1 ⊕ 0 = 1, so the binary is 0111.
As a formula, Gray = binary XOR (binary shifted right by one place).
4-bit Gray code sequence
Counting from 0 to 15. In the Gray code column, each row differs from the one above in exactly one bit.
| 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 |
Why Gray code exists
When a rotary encoder or a sensor moves to the next position, plain binary can change several bits at once: 7 to 8 is 0111 to 1000, four bits. If they don't flip at exactly the same moment, the reading is briefly wrong. In Gray code only one bit ever changes, so a reading is always one of the two neighbors.
Gray code also orders the rows and columns of Karnaugh maps, where neighboring cells must differ in one variable.
Frequently asked questions
What is Gray code?
Gray code is a way of counting in binary where each number differs from the next by exactly one bit. It is named after Frank Gray of Bell Labs, whose patent on it was granted in 1953.
How do you convert Gray code to binary?
Keep the first bit. Each binary bit after that is the XOR of the Gray bit in that place and the binary bit before it. 0100 in Gray code is 0111 in binary.
Gray code vs binary code: what's the difference?
Both write the same numbers with 0s and 1s, in a different order. Counting up in binary can flip many bits at once (0111 to 1000); in Gray code every step flips one. Binary suits arithmetic; Gray code suits position sensors, where a reading must never jump.