我有一个64位的线矢量;
wire [63:0] sout;
Run Code Online (Sandbox Code Playgroud)
我想计算这些位的总和,或者等价地计算一些的数量.
做这个的最好方式是什么?(它应该是可综合的)
Gre*_*reg 13
我更喜欢使用for循环,因为它们更容易扩展,并且需要更少的打字(因此不太容易出现拼写错误).
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)