SystemVerilog function clearing the return variable

Hi,

1.Is there a inbuilt function in system verilog for counting the number of ones in a given binary value? something like y= noofones(x);

  1. I have a function with a return value as shown below. This is returning the proper value at first but for the second onwards it is calculating keeping the old value
    int ones =0;
    function int noofones(input [31:0] re);
      for (int i=0; i<3; i++) begin
        ones = ones + (1 & re[i]);
      end
     return ones;
    endfunction

count_ones = noofones(4) gets the return value 1 

2nd call count_ones = noofones(4) getting the return value 2.

I want to clear the value before the second call but making something like below isn't working

  int ones =0;
    function int noofones(input [31:0] re);
      for (int i=0; i<3; i++) begin
        ones = ones + (1 & re[i]);
      end
     return ones;
     ones = 0;
    endfunction

Can anyone please tell me how to clear the previous values?

Thanks in advance

In reply to Ran@verification:

Have you read the SystemVerilog LRM?

Section 20.9:

The function $countbits counts the number of bits that have a specific set of values (e.g., 0, 1, X, Z) in a bit vector.

— $countbits ( expression , control_bit { , control_bit } )

This function returns an int equal to the number of bits in expression whose values match one of the control_bit entries.

For convenience, the following related functions are also provided:
— $countones ( expression ) is equivalent to $countbits(expression,'1).

The answer to your second question is that you have ‘ones’ declared as a global variable. It should be declared local to your function.