Search code examples
veriloghdlparameterization

Declaring a constant with a parameterized width


I want to declare constants with a parameterized width. For example, in this piece of code:

module mux2to1 #(parameter w = 4) (output [w-1:0] O, input [w-1:0] i0, i1, input Sel);
  assign O = (Sel)? i1 : i0;
endmodule

module M1 #(parameter n = 4) (input [n-1:0] A, input F, output [n+1:0] B);
  mux2to1#(n+2) mux (B, XXX, XXX, F);
endmodule

In the XXXs, I would like to put all 1s for one of them, and for the other, I would like to put 0s followed by a single 1.

How to do this?


Solution

  • You can use the replicated concatenation operator to construct a constant:

    mux2to1 #(n+2) mux (B, {(n+2){1'b1}}, {{(n+1){1'b0}}, 1'b1}, F);
    

    {(n+2){1'b1}} creates a constant of n+2 1'b1 bits. Since n is 4, {(n+2){1'b1}} is the same as {6{1'b1}}, which is the same as 6'b11_1111.

    {(n+1){1'b0}} is the same as 5'b0_0000, then just concatenate a single 1'b1 to that.