number of ones in array

前端 未结 2 428
悲&欢浪女
悲&欢浪女 2021-01-20 05:23

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

2条回答
  •  醉梦人生
    2021-01-20 06:21

    $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
    

提交回复
热议问题