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

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

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


8-3编码器程序:

1)利用for循环

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

 2)利用?:三目运算符

 1 module encoder8_3(a,b,c,d,e,f,g,h,out1,out2,out0,none_on);
 2   input a,b,c,f,d,e,g,h;
 3   output out0,out1,out2,none_on;
 4   wire [3:0]outvec;
 5   
 6   assign outvec=h?4'b0111:g?4'b0110:f?4'b0101:e?4'b0100:d?4'b0011:c?4'b0010:b?4'b0001:a?4'b0000:4'b1000;
 7   assign out0=outvec[0];
 8   assign out1=outvec[1];
 9   assign out2=outvec[2];
10   assign none_on=outvec[3];
11 endmodule 

 3)利用条件语句

 1 module encoder8_3(a,b,c,d,e,f,g,h,out1,out2,out0,none_on);
 2   input a,b,c,f,d,e,g,h;
 3   output out0,out1,out2,none_on;
 4   reg [3:0]outvec;
 5   
 6   always @(a or b or c or d or e or f or g or h)
 7   begin
 8   if(h) outvec=4'b0111;
 9     else if(g) outvec=4'b0110;
10       else if(f) outvec=4'b0101;
11         else if(e) outvec=4'b0100;
12           else if(d) outvec=4'b0011;
13             else if(c) outvec=4'b0010;
14               else if(b) outvec=4'b0001;
15                 else if(a) outvec=4'b0000;
16                   else     outvec=4'b1000;
17   end
18   assign out0=outvec[0];
19   assign out1=outvec[1];
20   assign out2=outvec[2];
21   assign none_on=outvec[3];
22 endmodule 
原文地址:https://www.cnblogs.com/SYoong/p/5948224.html