(This code was contributed by Jeff Cassidy at Isophase Computing (jeff@isophase-computing.ca, https://github.com/isophase), with edits by myself.)
Converts an unsigned binary number to the corresponding Reflected Binary Gray Code.
A Reflected Binary Gray Code starts from a simple 1-bit sequence 0,1 and can be constructed recursively for larger bit widths N. The sequence for N bits is build as follows:
For example:
The resulting Reflected Binary Gray Code has two useful properties:
The reverse function also exists.
`default_nettype none
module Binary_to_Gray_Reflected
#(
parameter WORD_WIDTH = 0
)
(
input wire [WORD_WIDTH-1:0] binary_in,
output reg [WORD_WIDTH-1:0] gray_out
);
localparam ZERO = {WORD_WIDTH{1'b0}};
initial begin
gray_out = ZERO;
end
function [WORD_WIDTH-1:0] binary_to_gray
(
input [WORD_WIDTH-1:0] binary
);
integer i;
reg [WORD_WIDTH-1:0] gray;
begin
for(i=0; i < WORD_WIDTH-1; i=i+1) begin
gray[i] = binary[i] ^ binary[i+1];
end
gray[WORD_WIDTH-1] = binary[WORD_WIDTH-1];
binary_to_gray = gray;
end
endfunction
always@(*) begin
gray_out = binary_to_gray(binary_in);
end
endmodule