Using it
Type a binary number to get its Gray code, or set Input to decimal and type an ordinary number. The steps show each bit worked out. Swap the boxes to turn a Gray code back into binary.
How to convert by hand
Binary to Gray: keep the first bit, then each next Gray bit is the XOR of that binary bit and the one before it. 0111 becomes 0, 0⊕1 = 1, 1⊕1 = 0, 1⊕1 = 0: 0100. In one line of code it's n XOR (n >> 1).
Gray to binary: keep the first bit, then each next binary bit is the XOR of the Gray bit and the binary bit you just wrote. Because each step needs the one before, decoding runs left to right.
4-bit Gray code
| 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 one bit at a time matters
Counting in plain binary from 7 to 8 flips four bits at once, 0111 to 1000. A sensor reading a turning wheel can't flip four bits at the same instant, so for a moment it might read any mix of them. In Gray code, 7 to 8 is 0100 to 1100: one bit changes, so a reading caught mid-change is off by one at most. That's why rotary encoders use it.
The same ordering labels the rows and columns of a Karnaugh map, so neighbouring cells differ in one variable. Frank Gray of Bell Labs named it the reflected binary code in his 1947 patent application, after the way the list can be built: write the list for one bit fewer, then the same list in reverse, and put 0 in front of the first half and 1 in front of the second.
Questions
What is 0111 in Gray code?
0100. That's 7 in decimal.
Is it spelt Gray or Grey?
Gray, after Frank Gray. Grey code is a common misspelling.
Can you do arithmetic in Gray code?
Not easily. It's made for counting and position sensing; convert to binary to add.
Sources
Added . What's new






