Search code examples
verilogsystem-verilog

Casting from int to parameterized-width logic


Given the parameters

parameter int eC,
parameter int cntW = ...

I have the following assignment:

logic [cntW-1:0] count;
logic [cntW-1:0] front;
logic [cntW-1:0] back;
assign count = condition ? front : back+eC+1 - front;

where back+eC+1 - front is promoted to a 32 bit int, which is wider than cntW. How can I explicitly cast int to the variable width cntW to suppress the warning that comes from the implicit conversion?

The warning is

Continuous assignment width mismatch
  5 bits (lhs) versus 32 bits (rhs).
  Source info: assign count = ((back >= front) ? (back - front) : (((back + 
  eC) + 1) - front));

Solution

  • First of all, the bare number 1 is implicitly a 32-bit signed decimal value. Operands in arithmetic expression get extended to the width of the largest operand before applying the operators. You can use 1'b1 which is an explicit 1-bit value. Also declare eC with the same width as the other variables

    typedef logic [cntW-1:0] cnt_t;
    parameter cnt_t eC;
    
    cnt_t count;
    cnt_t front;
    cnt_t back;
    assign count = condition ? front : back+eC+1'b1 - front;
    

    Another thing you do is use a cast

    assign count = condition ? front : cntW'(back+eC+1) - front;