Search code examples
veriloghdl8-bit

In Verilog, counting and outputting the number of 1's in an 8bit input?


What I am trying to do in my mind is take 8 1-bit inputs and count the 1's. Then represent those 1's.

01010111 should output 0101 (There are five 1's from input)

module 8to4 (in,out,hold,clk,reset);
input [7:0] in; //1 bit inputs
reg [7:0] hold; //possible use for case statement
output [3:0] out; //Shows the count of bits

always @(clk)
  begin
    out = in[0] + in[1] + in[2] + in[3] + in[4] + in[5] + in[6] + in[7]; //Adds the inputs from testbench and outputs it
  end
endmodule

Questions:

  • Is that the proper way to have 8 1-bit inputs? Or do I need to declare each variable as one bit ex: input A,B,C,D,E,F,G,H;
  • If my above code is close to being correct, is that the proper way to get out to display the count of 1's? Would I need a case statement?

I'm really new to verilog, so I don't even want to think about a test bench yet.


Solution

  • The way you wrote it is probably the better way of writing it because it makes it easier to parameterize the number of bits. But technically, you have one 8-bit input.

    module 8to4 #(parameter WIDTH=8) (input [WIDTH-1:0] in, 
                            output reg [3:0] out,hold,
                            input clk,reset);
      reg [WIDTH-1:0] temp;
      integer ii;
      always @(clk)
        begin
          temp = 0;
          for(ii=0; ii<WIDTH; i = i + 1)   
             temp = temp + in[ii];
          out <= temp;
        end
    endmodule