Void Star
Void Star

Reputation: 2521

Ones count system-verilog

I have a wire vector with 64 bits;

wire [63:0] sout;

I want to compute the sum of these bits or, equivalently, count the number of ones.

What is the best way to do this? (it should be synthesizable)

Upvotes: 6

Views: 29584

Answers (5)

EdwinG
EdwinG

Reputation: 11

The following synthesizable SystemVerilog functions do this for you:

$countbits(sout,'1);  // Counts the # of 1's
$countbits(sout,'0);  // Counts the # of 0's
$countones(sout);     // equivalent to $countbits(sout,'1)

The logic the synthesis tools will produce is a different story.

Ref: IEEE Std 1800-2012, Section 20.9

Upvotes: 0

user11034079
user11034079

Reputation: 21

The following solution uses a function to calculate the total number of set (to High) bits in a 64-bits wide bus:

function logic [6:0] AddBitsOfBus (
    input [63:0] InBus
);
    AddBitsOfBus[2:0] = '0;
    for (int k = 0; k < 64; k += 1) begin // for loop
        AddBitsOfBus[6:0] +=  {6'b00_0000, InBus[k]};
    end
endfunction

Upvotes: 0

Greg
Greg

Reputation: 19094

I prefer using for-loops as they are easier to scale and require less typing (and thereby less prone to typos).

SystemVerilog (IEEE Std 1800):

logic [$clog2($bits(sout)+1)-1:0] count_ones;

always_comb begin
  count_ones = '0;  
  foreach(sout[idx]) begin
    count_ones += sout[idx];
  end
end

Verilog (IEEE Std 1364-2005):

parameter WIDTH = 64;
// NOTE: $clog2 was added in 1364-2005, not supported in 1364-1995 or 1364-2001
reg [$clog2(WIDTH+1)-1:0] count_ones; 
integer idx;

always @* begin
  count_ones = {WIDTH{1'b0}};  
  for( idx = 0; idx<WIDTH; idx = idx + 1) begin
    count_ones = count_ones + sout[idx];
  end
end

Upvotes: 15

Jared Davis
Jared Davis

Reputation: 569

"Best" is rather subjective, but a simple and clear formulation would just be:

wire [6:0] sout_sum = sout[63] + sout[62] + ... + sout[1] + sout[0];

You might be able to think hard and come up with something that produces better synthesized results, but this is probably a good start until a timing tool says it's not good enough.

Upvotes: 0

toolic
toolic

Reputation: 62037

The $countones system function can be used. Refer to the IEEE Std 1800-2012, section "20.9 Bit vector system functions". It might not be synthesizable, but you did not list that as a requirement.

Upvotes: 0

Related Questions