Ones count system-verilog

Void Star picture Void Star · Nov 29, 2014 · Viewed 17.5k times · Source

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)

Answer

Greg picture Greg · Dec 1, 2014

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