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!).
The primary application of Gray code is in **glitch minimization** during signal transitions, especially in:
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]$.
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.
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
| Dec | Binary | Gray |
|---|---|---|
| 0 | 000 | 000 |
| 1 | 001 | 001 |
| 2 | 010 | 011 |
| 3 | 011 | 010 |
| 4 | 100 | 110 |
| 5 | 101 | 111 |
| 6 | 110 | 101 |
| 7 | 111 | 100 |