Verilog学习笔记简单功能实现(四)...............译码器和编码器

时间:2022-07-18 06:13:12

这里以简单的3-8译码器和8-3编码器为例:

module decoder3_8(a,out);
input [:]a;
output [:]out;
assign out='b1<<a;/*把最低位的1左移in位(根据in口输入的值)并赋予out*/
endmodule

8-3编码器程序:

1)利用for循环

 module encoder8_3(a,out,none_on);
input [:]a;
output [:]out;
output none_on;
reg [:]out;
reg none_on; //要在always块中赋值,必须为reg型数据 always @(a)
begin:local //这里必须要有定义顺序块的名字,因为后面要定义局部变量,有可能被实例化调用
integer i;
out=;
none_on=;
for(i=;i<;i=i+) //这里代表返回输入信号a的8位中,为1的最高位数,即高位优先编码;
begin //如果需要低位优先编码,只需要改成 for(i=7;i>=0;i=i-1)
if(a[i])
begin
out=i;
none_on=;
end
end
end
endmodule

2)利用?:三目运算符

 module encoder8_3(a,b,c,d,e,f,g,h,out1,out2,out0,none_on);
input a,b,c,f,d,e,g,h;
output out0,out1,out2,none_on;
wire [:]outvec; assign outvec=h?'b0111:g?4'b0110:f?'b0101:e?4'b0100:d?'b0011:c?4'b0010:b?'b0001:a?4'b0000:'b1000;
assign out0=outvec[];
assign out1=outvec[];
assign out2=outvec[];
assign none_on=outvec[];
endmodule

3)利用条件语句

 module encoder8_3(a,b,c,d,e,f,g,h,out1,out2,out0,none_on);
input a,b,c,f,d,e,g,h;
output out0,out1,out2,none_on;
reg [:]outvec; always @(a or b or c or d or e or f or g or h)
begin
if(h) outvec='b0111;
else if(g) outvec='b0110;
else if(f) outvec='b0101;
else if(e) outvec='b0100;
else if(d) outvec='b0011;
else if(c) outvec='b0010;
else if(b) outvec='b0001;
else if(a) outvec='b0000;
else outvec='b1000;
end
assign out0=outvec[];
assign out1=outvec[];
assign out2=outvec[];
assign none_on=outvec[];
endmodule