0
votes

Image. I am trying to solve a problem that was written below. I confused why my output was in undefined state. A "population count" circuit counts the number of '1's in an input vector. Build a population count circuit for a 255-bit input vector.

module top_module( 
    input [254:0] in,
    output [7:0] out );

    reg [7:0] counter=8'b0;
    reg [7:0] counter_next=8'b0;
    always @ (*)
        begin
            counter=counter_next;
        end
    always @ (*)
        begin
            for (int i=0; i<$bits(in);i++)
                counter_next=counter+in[i];
        end
    assign out=counter;
endmodule
1
You have a zero-delay loop in your code with the counter variable. - Serge

1 Answers

0
votes

confused why my output was in undefined state.

All HDL variables are undefined ('X' or 'U') until you give them a value.
Then, you add a value to that undefined value counter_next=counter+in[i]; which still gives undefined. So it stays that way.

Also you are using 'counter=counter_next' which suggest you have seen some existing HDL code and you are trying to copy it, but you do not understand why it is implemented that way. The 'next' system is used when there is a clock. You do not have a clock and as such it is superfluous here.

The code you are looking for is probably something like this:

output reg [7:0] out

always @( * )
begin
   out = 0;
   for (int i=0; i<$bits(in);i++)
      out =out+in[i];
end

Note that I am not using an extra variable counter here. All I do is make 'out' a reg type so I can use it directly.