3

I am trying to count the number of ones in a 4-bit binary number in Verilog, but my output is unexpected. I've tried several approaches; this is the one 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
toolic
  • 57,801
  • 17
  • 75
  • 117
Omar Sherif
  • 55
  • 1
  • 3

2 Answers2

5

First, you can't assign the variable twice.

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

This is more like what you need:

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

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

endmodule
N8TRO
  • 3,348
  • 3
  • 22
  • 40
  • I've tried this approach before and i tried it again now and still no output occurs – Omar Sherif Oct 30 '13 at 23:40
  • It works for me.. It must be something else. What tools are you using? Are you setting this as you're top-level module? – N8TRO Oct 30 '13 at 23:52
  • i am using verilogger pro and i only have this module in the project – Omar Sherif Oct 30 '13 at 23:57
  • How are you checking the output? Is it possible your testing methods are wrong? – N8TRO Oct 30 '13 at 23:59
  • through a timing diagram, i've tried it for simple structural model circuits and it works but it doesn't seem to work for behavioral or dataflow – Omar Sherif Oct 31 '13 at 00:04
  • I'm not too familiar with verilogger. I just programmed an FPGA and it worked fine. I also simulated it and it worked in the simulation as well. I suspect the inconsistency is in how the tools are used. – N8TRO Oct 31 '13 at 00:11
  • 1
    ok figured it out it,i had to change the sim from indep to diagram&project thnx for the help – Omar Sherif Oct 31 '13 at 00:12
3

$countones can be used for this purpose (refer to 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

Output:

in=xxxx one=0
in=0000 one=0
in=0001 one=1
in=1101 one=3
toolic
  • 57,801
  • 17
  • 75
  • 117