Just to help someone else who might be searching for the same thing...
Here is a modified and fixed version of the code using the preferred Verilog 2001 syntax for module ports
Code Verilog - [expand] |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| module gr2bi #(
parameter N = 4
) (
input [N-1:0] gr,
output reg [N-1:0] bi
);
integer i = N-2;
always @(*) begin
bi[N-1] = gr[N-1];
for (i=N-2;i>=0;i=i-1)
bi[i] = gr[i] ^ bi[i+1];
end
endmodule |
and here is a testbench that proves it works.
Code Verilog - [expand] |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| `timescale 1ns/1ps
module tb;
parameter N = 4;
reg [N-1:0] gr;
wire [N-1:0] bi;
initial begin
gr = 0;
repeat (2**N) begin
#10;
gr = gr + 1;
end
end
gr2bi #(
.N (N)
) UUT (
.gr (gr),
.bi (bi)
);
endmodule |
- - - Updated - - -
Actually here is my preferred version of both an N-bit binary-to-gray and N-bit gray-to-binary conversion.
binary to gray
Code Verilog - [expand] |
1
2
3
4
5
6
7
8
9
10
| module b2g #(
parameter N = 4
) (
output [N-1:0] g,
input [N-1:0] b
);
assign g = b ^ (b >> 1);
endmodule |
gray to binary:
Code Verilog - [expand] |
1
2
3
4
5
6
7
8
9
10
11
12
13
| module g2b #(
parameter N = 4
) (
output [N-1:0] b,
input [N-1:0] g
);
generate genvar i;
for (i=0; i<N; i=i+1) begin : gen_bin
assign b[i] = ^g[N-1:i];
end
endgenerate
endmodule |
Testbench:
Code Verilog - [expand] |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
| `timescale 1ns/1ps
module tb;
parameter N = 4;
reg [N-1:0] bin;
wire [N-1:0] gray;
wire [N-1:0] binary;
initial begin
bin = 0;
repeat (2**N) begin
#10;
bin = bin + 1;
end
end
// my preferred versions of both conversions
// binary to gray
b2g #(.N(N)) uut_b2g (
.g (gray),
.b (bin)
);
// gray to binary
g2b #(.N(N)) uut_g2b (
.b (binary),
.g (gray)
);
initial begin
$monitor ("binary = %b, gray = %b, binary %b", bin, gray, binary);
end
endmodule |
Note: this gray to binary conversion doesn't require the feedback of the bi[i+1] to produce the bi
bit (it only relies on the gray value). Haven't tried synthesizing both my preferred version and the modified original, but it seems to me the one with the feedback might result in something slightly slower as the bi bits have to propagate through the bit width of the converted value. Then again synthesis may end up with the same circuit in the end.