(Assume Mux4Way
has been already implemented)
/**
* 4-way 16-bit multiplexor:
* out = a if sel == 00
* b if sel == 01
* c if sel == 10
* d if sel == 11
*/
CHIP Mux4Way16 {
IN a[16], b[16], c[16], d[16], sel[2];
OUT out[16];
PARTS:
// Put your code here:
Mux4Way(a=a[0],b=b[0],c=c[0],d=d[0],sel=sel,out=out[0]);
Mux4Way(a=a[1],b=b[1],c=c[1],d=d[0],sel=sel,out=out[1]);
Mux4Way(a=a[2],b=b[2],c=c[2],d=d[0],sel=sel,out=out[2]);
Mux4Way(a=a[3],b=b[3],c=c[3],d=d[0],sel=sel,out=out[3]);
Mux4Way(a=a[4],b=b[4],c=c[4],d=d[0],sel=sel,out=out[4]);
Mux4Way(a=a[5],b=b[5],c=c[5],d=d[0],sel=sel,out=out[5]);
Mux4Way(a=a[6],b=b[6],c=c[6],d=d[0],sel=sel,out=out[6]);
Mux4Way(a=a[7],b=b[7],c=c[7],d=d[0],sel=sel,out=out[7]);
Mux4Way(a=a[8],b=b[8],c=c[8],d=d[0],sel=sel,out=out[8]);
Mux4Way(a=a[9],b=b[9],c=c[9],d=d[0],sel=sel,out=out[9]);
Mux4Way(a=a[10],b=b[10],c=c[10],d=d[0],sel=sel,out=out[10]);
Mux4Way(a=a[11],b=b[11],c=c[11],d=d[0],sel=sel,out=out[11]);
Mux4Way(a=a[12],b=b[12],c=c[12],d=d[0],sel=sel,out=out[12]);
Mux4Way(a=a[13],b=b[13],c=c[13],d=d[0],sel=sel,out=out[13]);
Mux4Way(a=a[14],b=b[14],c=c[14],d=d[0],sel=sel,out=out[14]);
Mux4Way(a=a[15],b=b[15],c=c[15],d=d[0],sel=sel,out=out[15]);
}
As you can see, this code looks quite inelegant. How can I deal with this repetitive code? I'm new to HDL, so I apologize for this trivial question. Is there the concept of loops (or something like it) in HDL?
-
3\$\begingroup\$ Most languages have a construct that allows you to instantiate arrays of entities. For instance, VHDL has a "generate" statement. I don't recognize your HDL, what language are you using? \$\endgroup\$uint128_t– uint128_t2016年12月22日 01:36:51 +00:00Commented Dec 22, 2016 at 1:36
2 Answers 2
In verilog you use a generate like:
genvar i;
generate
for (i = 0; i < 16 ; i = i + 1) begin: muxes
Mux4Way m(.a(a[i]),.b(b[i]),.c(c[i]),.d(d[i]),.sel(sel),.out(out[i]));
end
endgenerate
The best way to implement a mux is to use the array-subscript operator (we don't need to construct a larger mux using smaller ones, the HDL synthesizer does this for us). The SystemVerilog code would look like this:
logic [1:0] select; // Two bit array index
logic [15:0] in[3:0]; // Four 16-bit numbers
logic [15:0] out; // 16-bit output
always_comb out = in[sel];
/* If the array "in" is not available, you can create it as:
always_comb in[0] = a;
always_comb in[1] = b;
...
always_comb in[3] = d;
*/