Pad or truncate vector assignments based on parameter values

Viewed 61

I have a module that can be configured with two parameters. Depending on the values of these parameters, I either need to pad or truncate an output vector when assigning it to an input vector. For example:

module my_mod(vector_in,
        vector_out);
    
    parameter IN_BITS = 10;
    parameter OUT_BITS = 8;
    // or
    // parameter IN_BITS = 8;
    // parameter OUT_BITS = 10;
    
    input [IN_BITS-1:0] vector_in;
    output[OUT_BITS-1:0] vector_out;
    
    // assign vector_out to vector_in
    // when OUT_BITS > IN_BITS => pad MSB's with zeors
    // when OUT_BITS < IN_BITS => truncate LSB's of in
    // else just assign
endmodule

What is the best way to do this?

1 Answers

One clean way is to use a generate if construct. If there are more out bits than in bits, padding can be achieved by subtracting the parameters. Otherwise, use the out parameter to bit-slice the input; this should not be strictly be necessary, but it might make the design intent more obvious.

module my_mod (vector_in, vector_out);
    parameter IN_BITS  = 10;
    parameter OUT_BITS =  8;

    input  [IN_BITS -1:0] vector_in;
    output [OUT_BITS-1:0] vector_out;

    if (OUT_BITS > IN_BITS) begin
        assign vector_out = { {(OUT_BITS-IN_BITS){1'b0}} , vector_in };
    end else begin
        assign vector_out = vector_in[OUT_BITS-1 : 0];
    end
endmodule

Refer to IEEE Std 1800-2017, section 27. Generate constructs

Related