Writing a simple function to count number of ones in a vector

Viewed 239

As a task for learning how to write functions in Verilog, I am trying to write a function that just counts the number of ones in a given vector:

module m ();
 parameter n = 4;
function integer count_ones (input [n-1:0] a);
   
    for (integer i = 0 ; i<n ; i=i+1)
      begin
        if (a[i] ==1'b1)begin
          count_ones=count_ones+1;
        end
        
      end
    
    endfunction
initial begin 
reg [3:0] a = 4'b1;
integer result =  count_ones (a);
  
  $display("output is ", result);
end 
endmodule 

The result is displayed as x. So what is the error in this code ?

1 Answers

You declare count_ones as type integer, which is a 4-state type, and its default value is x. Also, count_ones=count_ones+1; keeps count_ones equal to x.

You should initialize count_ones inside the function.

function integer count_ones (input [n-1:0] a);
    count_ones = 0;

Keep in mind that there is a built-in $countones system function. Refer to IEEE Std 1800-2017, section 20.9 Bit vector system functions.

Related