Tuesday, August 9, 2011

How to calculate the sum of data in a queue of bits in SystemVerilog?


    The built-in array method sum() will return a value according to the type of queue.
    such as:
    bit flags[$];
    ....
    flags.sum() will return 0 or 1 because the type of queue is bit

    Solution

    To actually sum the queue data use:
    mysum = flags.sum() with (int'(item));
    Below is an example for reference:
    module test;
     bit flags[$];
     int mysum;
     initial
     begin
     flags[0] =1;
     flags[1]=1;
     mysum = flags.sum();  //this will return 0 or 1
     $display("%0d",mysum);
     mysum = flags.sum() with (int'(item));  //this will return the total value of every element.
     $display("%0d",mysum);
    end
    endmodule