Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verilog: Adding individual bits of a register (combinational logic, register width is parameterizable)

I am trying to come up with a way to add individual bits of a register. eg, if regA = 111000 then regB = 3 (Sum of bits of regA). 1) Is there any synthesizable function/operator in Verilog or SystemVerilog which I can directly use to do this operation?

If not, then maybe the problem is a little interesting, especially because the operation has to be done in one clock cycle (pure combinational logic) and the register width is parameterizable.

2) In case there is no inbuilt Verilog or SystemVerilog operator then what can be done?

Thanks, Ujjwal

like image 242
Ujjwal Avatar asked Aug 30 '25 17:08

Ujjwal


1 Answers

Verilog (IEEE Std 1364-2001 or newer):

integer i;
always @* begin
  B = WIDTH_LOG2'b0;
  for (i=0; i<WIDTH; i=i+1)
    B = B + A[i];
end

SystemVerilog (IEEE Std 1800-2005 or newer):

always_comb begin
  B = '0; // fill 0
  foreach(A[i])
    B += A[i];
end

Both will synthesize to combination logic. No latches or flops.

SystemVerilog does have $countones(), but I'm unsure if it is synthesizable. Ff it is then: always_comb B = $countones(A)

like image 130
Greg Avatar answered Sep 03 '25 22:09

Greg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!