Search code examples
verilog

Reduce array to sum of elements


I am trying to reduce a vector to a sum of all it elements. Is there an easy way to do this in verilog?

Similar to the systemverilog .sum method.

Thanks


Solution

  • Verilog doesn't have any built-in array methods like SV. Therefore, a for-loop can be used to perform the desired functionality. Example:

    parameter N = 64;
    integer i;
    reg [7:0] array [0:N-1]
    reg [N+6:0] sum; // enough bits to handle overflow
    
    always @*
    begin
      sum = {(N+7){1'b0}}; // all zero
      for(i = 0; i < N; i=i+1)
        sum = sum + array[i];
    end