1. 程式人生 > >Verilog 二進位制到格雷碼的相互轉換

Verilog 二進位制到格雷碼的相互轉換

/*
Decimal   Binary   Gray-Code
00        0000     0000
01        0001     0001
02        0010     0011
03        0011     0010
04        0100     0110
05        0101     0111
06        0110     0101
07        0111     0100
08        1000     1100
09        1001     1101
10        1010     1111
11        1011     1110
12        1100     1010
13        1101     1011
14        1110     1001
15        1111     1000
*/

module Gray2Bin(iGray, oBin);
 input  [3:0] iGray;
 output [3:0] oBin;
 
 /////////////////////////////////////// 
 reg [3:0] oBin;
  
 always @(iGray)
  begin
   case(iGray) 
    4'b0000: oBin = 4'b0000;
    4'b0001: oBin = 4'b0001;
    4'b0011: oBin = 4'b0010;
    4'b0010: oBin = 4'b0011;
    4'b0110: oBin = 4'b0100;
    4'b0111: oBin = 4'b0101;
    4'b0101: oBin = 4'b0110;
    4'b0100: oBin = 4'b0111;
    4'b1100: oBin = 4'b1000;
    4'b1101: oBin = 4'b1001;
    4'b1111: oBin = 4'b1010;
	4'b1110: oBin = 4'b1011;
    4'b1010: oBin = 4'b1100;
    4'b1011: oBin = 4'b1101;
    4'b1001: oBin = 4'b1110;
    4'b1000: oBin = 4'b1111;    
   endcase    
  end
  
endmodule

module Bin2Gray(iBin, oGray);
 input [3:0] iBin;
 output [3:0] oGray;
 
 ////////////////////////////////////////
 reg [3:0] oGray;

 always @(iBin)
  begin
   case(iBin)
    4'b0000: oGray = 4'b0000;    
    4'b0001: oGray = 4'b0001;
    4'b0010: oGray = 4'b0011;
    4'b0011: oGray = 4'b0010;
    4'b0100: oGray = 4'b0110;
    4'b0101: oGray = 4'b0111;
    4'b0110: oGray = 4'b0101;
    4'b0111: oGray = 4'b0100;
    4'b1000: oGray = 4'b1100;
	4'b1001: oGray = 4'b1101;
    4'b1010: oGray = 4'b1111;
    4'b1011: oGray = 4'b1110;
    4'b1100: oGray = 4'b1010;
    4'b1101: oGray = 4'b1011;
    4'b1110: oGray = 4'b1001;
    4'b1111: oGray = 4'b1000;
   endcase
  end

endmodule