Digital Logic

Gray Code

A binary encoding where consecutive values differ by exactly one bit, minimizing transition errors.

Detailed Explanation

In standard binary, counting from 7 to 8 (0111 to 1000) changes all four bits. In gray code, consecutive values differ by exactly one bit, eliminating multi-bit transition hazards. Conversion between binary and gray code uses XOR operations.

Gray code is essential for clock domain crossing—a gray-coded pointer crossing domains may be sampled during transition, but the resulting value is either the old value or new value, never a corrupted in-between state.

Code Example

systemverilog
// Binary to Gray conversion
assign gray = binary ^ (binary >> 1);

// Gray to Binary conversion
always_comb begin
  binary[N-1] = gray[N-1];
  for (int i = N-2; i >= 0; i--)
    binary[i] = binary[i+1] ^ gray[i];
end