生活随笔
收集整理的這篇文章主要介紹了
Verilog——格雷码和二进制码转换的Verilog实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
格雷碼和二進制碼轉換的Verilog實現
1. 二進制碼轉換為格雷碼:
- 轉換原則:格雷碼最高位gray[N]等于二進制碼最高位gray[N],格雷碼第n位等于二進制碼第(n+1)位異或二進制碼第n位,n∈[0,N-1],即:
gray
[N
] = binary
[N
]
gray
[n
] = binary
[n
+1] ^ binary
[n
], 其中n∈
[0,N
-1]
`timescale 1ns/1psmodule bin2gray
#(parameter W = 8 //位寬
)
(input [W-1 : 0] binary_code ,//二進制碼output [W-1 : 0] gray_code //格雷碼
);parameter N = W-1 ;//最高位//gray_code[N]
assign gray_code[N] = binary_code[N];
//gray_code[N-1 : 0]
generategenvar i;for(i = 0; i < N; i = i + 1) beginassign gray_code[i] = binary_code[i+1] ^ binary_code[i];end
endgenerateendmodule
`timescale 1ns/1psmodule tb_bin2gray;reg [7:0] binary_code ;
wire [7:0] gray_code ;
//---
integer i ;//---------------------------------
bin2gray
#(.W (8 )//位寬
)
bin2gray_inst
(.binary_code(binary_code),.gray_code (gray_code )
);initial beginfor(i = 0; i < 256; i = i + 1) beginbinary_code = #10 i;end#200;for(i = 0; i < 256; i = i + 1) beginbinary_code = #10 ({$random} % 256);end
endendmodule
2. 格雷碼轉換為二進制碼:
- 轉換原則:二進制碼最高位bin[N]等于格雷碼最高位gray[N],二進制碼第n位等于二進制碼(n+1)位異或格雷碼第n位,n∈[0,N-1],即:
binary
[N
] = gray
[N
]
binary
[n
] = binary
[n
+1] ^ gray
[n
], 其中n∈
[0,N
-1]
`timescale 1ns/1psmodule gray2bin
#(parameter W = 8 //位寬
)
(input [W-1 : 0] gray_code ,//二進制碼output [W-1 : 0] binary_code //格雷碼
);parameter N = W-1 ;//最高位//binary_code[N]
assign binary_code[N] = gray_code[N];
//binary_code[N-1 : 0]
generategenvar i;for(i = 0; i < N; i = i + 1) beginassign binary_code[i] = binary_code[i+1] ^ gray_code[i];end
endgenerateendmodule
`timescale 1ns/1psmodule tb_gray2bin;reg [7:0] gray_code ;
wire [7:0] binary_code ;
//---
integer i ;
gray2bin
#(.W (8 ) //位寬
)
gray2bin_inst
(.gray_code (gray_code ), .binary_code(binary_code)
);initial beginfor(i = 0; i < 256; i = i + 1) begingray_code = #10 i;end
endendmodule
總結
以上是生活随笔為你收集整理的Verilog——格雷码和二进制码转换的Verilog实现的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。