How to use $countones()


#1

How exactly do I use $countones()? I would like to find out number of bits that are equal to 1 in a variable. I would also like to find out the number of 0s in the variable


#2

It returns the number of bits that have the value 1 in a variable. I typically use $countones(var_name) to quickly find out if a variable if one-hot encoded.

$countones() is actually a convenience function associated with another system function $countbits().

$countbits(expression, control_bit {, control_bit});
//returns the number of bits in the expression having the value 1
$countbits(expression, '1);
//returns the number of bits in the expression that have value 0 or X
$countbits(expression, '0, 'x);
//returns the number of bits in the expression that have value X or Z
$countbits(expression, 'x, 'z);

The control_bit argument has to be a 1-bit logic.

There are a few convenience functions associated with $countbits():

// counts the number of 1s
$countones()
// returns true if $countbits(expression, '1)==1
$onehot() 
// returns true if $countbits(expression, '1)<=1
$onehot0() 
// returns true if any bits are X or Z
$isunknown() 

Full Example

program automatic utils;
    logic [31:0] monkey;
    initial begin
        monkey = 32'hxx1801zz;
        $display("Count ones    : %0d", $countbits(monkey, '1));
        $display("Count Xs      : %0d", $countbits(monkey, 'X));
        $display("Xs            : %0d", $countbits(monkey, 'X));
        monkey = 32'h00008000;
        $display("0x%x Is one hot : %0d", monkey, $onehot(monkey));
        monkey = 32'h80008000;
        $display("0x%x Is one hot : %0d", monkey, $onehot(monkey));
        monkey = 32'h00000000;
        $display("0x%x Is one hot : %0d", monkey, $onehot(monkey));
        $display("0x%x Is onehot0 : %0d", monkey, $onehot0(monkey));
    end
endprogram

Output

Count ones    : 3
Count Xs      : 8
Xs            : 8
0x00008000 Is one hot : 1
0x80008000 Is one hot : 0
0x00000000 Is one hot : 0
0x00000000 Is onehot0 : 1

You can refer to this article
https://www.systemverilog.io/ten-utilities#countbits