Easy · Combinational Logic
Implement an 8-bit binary-to-Gray encoder and an 8-bit Gray-to-binary decoder in one module. The two converters are independent and work at the same time.
In the (reflected binary) Gray code, consecutive numbers differ in exactly one bit. That property is why Gray-coded counters are used to pass FIFO pointers across clock domains: if a pointer is sampled while it changes, at most one bit is in flight, so the sampled value is either the old or the new value, never garbage.
| Port | Dir | Width | Meaning |
|---|---|---|---|
bin_in | input | 8 | Unsigned binary value to encode. |
gray_out | output | 8 | Gray code of bin_in. |
gray_in | input | 8 | Gray-coded value to decode. |
bin_out | output | 8 | Binary value whose Gray code is gray_in. |
gray_out depends only on bin_in, and bin_out depends only on gray_in. Both are purely combinational.
Encode (binary b → Gray g): each Gray bit is the XOR of the binary bit and the binary bit above it. The top bit is copied.
g[7] = b[7]g[i] = b[i+1] ^ b[i] for i = 6 … 0Decode (Gray g → binary b): each binary bit is the XOR of all Gray bits at or above it, which can be computed from the top down:
b[7] = g[7]b[i] = b[i+1] ^ g[i] for i = 6 … 0Decoding is the inverse of encoding: feeding gray_out back into gray_in returns bin_in on bin_out.
| binary (decimal) | binary | Gray |
|---|---|---|
| 0 | 0000_0000 | 0000_0000 |
| 1 | 0000_0001 | 0000_0001 |
| 2 | 0000_0010 | 0000_0011 |
| 3 | 0000_0011 | 0000_0010 |
| 4 | 0000_0100 | 0000_0110 |
| 127 | 0111_1111 | 0100_0000 |
| 128 | 1000_0000 | 1100_0000 |
| 255 | 1111_1111 | 1000_0000 |
So bin_in = 8'd3 gives gray_out = 8'b0000_0010, and gray_in = 8'b1100_0000 gives bin_out = 8'd128.
Encoding is a one-liner with a shift and an XOR. Decoding needs a chain: in always_comb, keep a running XOR in a local variable and walk a for loop from bit 7 down to bit 0, updating the variable with gray_in[i] and copying it into bin_out[i]. (Reading bin_out[i+1] while still assigning bin_out in the same block also simulates correctly, but Verilator warns about it with ALWCOMBORDER.)
Sign up free to solve Binary / Gray Code Converter in your browser.