自然二进制:Bn-1Bn-2….B2B1B0
格雷码 :Gn-1Gn-2…G2G1G0
自然二进制转格雷码公式: Gi = Bi ,i = n-1
Gi = Bi xor Bi+1 ,i = 0:n-2
格雷码转自然二进制:Bi = Gi,i = n-1
Bi-1 = Gi-1 xor Bi,i = 1:n-1
一般的,普通二进制码与格雷码可以按以下方法互相转换:
二进制码->格雷码(编码):从最右边一位起,依次将每一位与左边一位异或(XOR)(http://bk.7tmusic.com/lemma-php/dispose/view.php/379209.htm),作为对应格雷码该位的值,最左边一位不变(相当于左边是0);
格雷码-〉二进制码(解码):从左边第二位起,将每位与左边一位解码后的值异或,作为该位解码后的值(最左边一位依然不变).
modele bin2gry(Gry,Bin)
parameter length = 8;
output [length-1:0] Gry;
input [length-1:0] Bin;
reg [length-1:0] Gry;
integer i;
always @ (Bin)
begin
for(i=0;i<length-1;i++)
Gry[i]=Bin[i]^Bin[i+1];
Gry[i]=Bin[i];
end
endmodule
modele gry2bin(Gry,Bin)
parameter length = 8;
output [length-1:0] Gry;
input [length-1:0] Bin;
reg [length-1:0] Bin;
integer i;
always @ (Gry)
begin
Bin[length-1]=Gry[length-1];
for(i=length-2;i>=0;i--)
Bin[i]=Bin[i+1]^Gry[i];
end
endmodule