Skip to content
BinaryTo

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

Direction

Gray code

How to convert binary to Gray code

  1. 01

    Keep the first bit

    The leftmost Gray bit is the same as the leftmost binary bit.

  2. 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.

  3. 03

    Read the result

    For 0111: 0, then 0 ⊕ 1 = 1, 1 ⊕ 1 = 0 and 1 ⊕ 1 = 0, so the Gray code is 0100.

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.

4-bit Gray code sequence
DecimalBinaryGray code
000000000
100010001
200100011
300110010
401000110
501010111
601100101
701110100
810001100
910011101
1010101111
1110111110
1211001010
1311011011
1411101001
1511111000

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.