Skip to content

Instantly share code, notes, and snippets.

@shtaxxx
Created October 18, 2013 09:11
Show Gist options
  • Save shtaxxx/7038809 to your computer and use it in GitHub Desktop.
Save shtaxxx/7038809 to your computer and use it in GitHub Desktop.
Gray Code Encoder and Decoder
module test_gray_code;
parameter DWIDTH = 10;
function [DWIDTH-1:0] to_gray;
input [DWIDTH-1:0] in;
to_gray = in ^ (in >> 1);
endfunction
function [DWIDTH-1:0] to_binary;
input [DWIDTH-1:0] in;
integer i, j;
begin
for(i=0; i<DWIDTH; i=i+1) begin
to_binary[i] = 1'b0;
for(j=0; j<DWIDTH; j=j+1) begin
if(j >= i) to_binary[i] = to_binary[i] ^ in[j];
end
end
end
endfunction
reg [DWIDTH :0] num;
reg [DWIDTH-1:0] g;
reg [DWIDTH-1:0] d;
initial begin
for(num=0; num<2**DWIDTH; num=num+1) begin
g = to_gray(num);
d = to_binary(g);
$display("bin=%x gray=%x decode=%x match?=%b", num, g, d, num==d);
end
$finish;
end
endmodule
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment