Skip to content
BetterDL

Gray code

Also called: reflected binary code, reflected binary, Gray code ordering, Gray order, unit-distance code

A binary code in which consecutive values differ in exactly one bit, including the wrap from last back to first. The 2-bit sequence is 00, 01, 11, 10.

A Gray code lists binary patterns so that each step changes exactly one bit. The standard 2-bit sequence is 00, 01, 11, 10, and the 3-bit one is 000, 001, 011, 010, 110, 111, 101, 100. In both, the jump from the last pattern back to the first also changes just one bit, so the sequence is cyclic.

Compare ordinary binary: going from 01 to 10 flips two bits at once, and 011 to 100 flips three.

Building it by reflection. Take the (n−1)-bit list, write it forwards with a 0 in front, then backwards with a 1 in front. From 0, 1 you get 00, 01, 11, 10. Repeat to get the 3-bit list.

Converting binary to Gray. Keep the most significant bit. Each other Gray bit is the XOR of a binary bit and the binary bit to its left. In the table above, G2 = B2, G1 = , G0 = .

Converting Gray to binary. Keep the MSB. Each next binary bit is the XOR of the binary bit you just found and the next Gray bit.

Why it matters here. A karnaugh map labels its axes in Gray order, so touching cells differ in one variable and can be grouped. Gray codes are also used in rotary position sensors and in counters that cross clock domains, where changing only one bit at a time avoids reading a half-changed value.

G2G1G0
000000
001001
010011
011010
100110
101111
110101
111100

Worked examples

Example

Binary to Gray and back

Convert 1011 to Gray code, then convert the result back.

  1. 1.

    Keep the MSB: G3 = 1.

  2. 2.

    G2 = 1 ⊕ 0 = 1. G1 = 0 ⊕ 1 = 1. G0 = 1 ⊕ 1 = 0. Gray code: 1110.

  3. 3.

    Back to binary: b3 = G3 = 1.

  4. 4.

    b2 = b3 ⊕ G2 = 1 ⊕ 1 = 0. b1 = b2 ⊕ G1 = 0 ⊕ 1 = 1. b0 = b1 ⊕ G0 = 1 ⊕ 0 = 1.

  5. 5.

    Result: 1011, the number we started with. ✓

Example

Why K-map labels go 00, 01, 11, 10

Check the bit changes between neighboring labels in both orders.

  1. 1.

    Gray order: 00→01 (1 bit), 01→11 (1 bit), 11→10 (1 bit), and the wrap 10→00 (1 bit).

  2. 2.

    Binary order: 00→01 (1 bit), 01→10 (2 bits), 10→11 (1 bit), and the wrap 11→00 (2 bits).

  3. 3.

    Only Gray order makes every pair of neighbors, including across the edge, differ in one variable.

Common mistakes

  • Treating a Gray code pattern as an ordinary binary number. 11 in the third K-map column means B = 1, C = 1, not "column 3".

  • Converting Gray to binary by XORing neighboring Gray bits. Each step uses the binary bit you just computed.

  • Forgetting the wrap. The last and first Gray codes also differ in one bit, which is why K-maps wrap around.

Practice Gray code

Interactive questions with instant feedback and a worked solution for every wrong answer.

Learn it step by step

Gray code is taught in Karnaugh Maps and Number Systems.