Verilog number of ones in an array

I am trying to find out the number of ones in a 4-bit binary number in verilog, but no output occurs. I've tried several approaches, this is what I think should work, but it doesn't.

module ones(one,in);
input [3:0]in;
output [1:0]one;

assign one = 2'b00; 
assign one = one+in[3]+in[2]+in[1]+in[0] ;

endmodule

      

+2


source to share


2 answers


First, you cannot assign this variable twice.

Second, your range is off, 2 bits can only go from 0 to 3. You need a 3-bit output to count to 4.



This is more like what you want:

module ones(
  output wire [2:0] one,
  input wire [3:0] in
);

assign one = in[3]+in[2]+in[1]+in[0] ;

endmodule

      

+4


source


$countones

useful in testbenches, but not synthesized (see IEEE Std 1800-2012 , 20.9 bit vector system functions)



module tb;

reg [3:0] in;
wire [2:0] one = $countones(in);
initial begin
    $monitor("in=%b one=%d", in, one);
    #1 in = 4'b0000;
    #1 in = 4'b0001;
    #1 in = 4'b1101;
end

endmodule

/*

in=xxxx one=0
in=0000 one=0
in=0001 one=1
in=1101 one=3

*/

      

+3


source







All Articles