EcrioniX Logic

The Magic of Gray Codes

1. What is Gray Code?

Gray code, named after Frank Gray, is a binary numeral system where two successive values differ in only **one bit position**. This is fundamentally different from standard binary, where multiple bits can change simultaneously (e.g., $7 \to 8$ is `0111` $\to$ `1000`, changing 4 bits!).

2. Why do we need it?

The primary application of Gray code is in **glitch minimization** during signal transitions, especially in:

  • CDC (Clock Domain Crossing): In Async FIFOs, passing binary pointers between clock domains is dangerous. If a multi-bit change is sampled mid-transition, it can result in a wild, invalid value. Gray codes ensure that any sampling error only results in an off-by-one error (reading the old value or the new one), which is safe.
  • Karnaugh Maps: K-Map axes are labeled in Gray code so that adjacent cells differ by only one variable, allowing for logical grouping.
  • Rotary Encoders: Used in position sensors to prevent read errors.

3. Conversion Logic

Binary to Gray

To convert a binary number $B$ to Gray code $G$:

\[ G = B \oplus (B \gg 1) \]

The MSB is kept the same. Each subsequent bit $G[i]$ is the XOR of $B[i]$ and $B[i+1]$.

Gray to Binary

To convert Gray code $G$ back to binary $B$:

\[ B[i] = G[i] \oplus B[i+1] \]

This is an iterative process. The MSB is the same. The next binary bit is the XOR of the current Gray bit and the *previous* calculated binary bit.

SystemVerilog Implementation

module bin2gray #(
    parameter WIDTH = 4
)(
    input  logic [WIDTH-1:0] bin,
    output logic [WIDTH-1:0] gray
);
    // G = B ^ (B >> 1)
    assign gray = (bin >> 1) ^ bin;

endmodule

module gray2bin #(
    parameter WIDTH = 4
)(
    input  logic [WIDTH-1:0] gray,
    output logic [WIDTH-1:0] bin
);
    always_comb begin
        for (int i = 0; i < WIDTH; i++) begin
            // B[i] = ^(G >> i) 
            // XORing all bits from MSB down to i
            bin[i] = ^(gray >> i);
        end
    end
endmodule

Configuration

Conversion Mode
Bit Width 4 Bits
Input Value

Truth Table (3-Bit)

DecBinaryGray
0000000
1001001
2010011
3011010
4100110
5101111
6110101
7111100
Logic Gate Visualizer