StringMash.com

Gray code converter

Binary to reflected binary and back, one XOR at a time.

Conversion
4 characters
Updates as you type
Decimal7
Binary0111

Show the steps
  1. Binary: 0111.
  2. The first Gray bit is the same as the first binary bit.
  3. Bit 2: 0 XOR 1 = 1.
  4. Bit 3: 1 XOR 1 = 0.
  5. Bit 4: 1 XOR 1 = 0.
  6. In one step: Gray = binary XOR (binary shifted right by one).

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

Each row differs from the one above it in exactly one bit, and the last row (1000) differs from the first in one bit too.
DecimalBinaryGray code
000000000
100010001
200100011
300110010
401000110
501010111
601100101
701110100
810001100
910011101
1010101111
1110111110
1211001010
1311011011
1411101001
1511111000

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