Forum Discussion

Altera_Forum's avatar
Altera_Forum
Icon for Honored Contributor rankHonored Contributor
15 years ago

to find out the number of "1"

hi,everyone

i need to find out the number of "1" in a input (a),

now ,i thik i could add every bit of input (a) to get the resut,

just like : assign b=a[0]+a[0]+a[1]+a[2]+a[3]+a[4]; -----code(1)

so , if a==5'd10==5'b01010 then b=2 , it's right

but ,now, the width of a is 2023 ,it is too large.

so , for me ,it is a big trouble for me to write like code(1) ,it will cost too much time.

so i wright like this:

module jj(data_in,weight_out);

parameter IN_WIDTH=10;

input [IN_WIDTH-1:0 ] data_in;

output [11:0] weight_out;

reg [11:0] a;

always @ (*) begin

integer i;

for(i=0;i<IN_WIDTH;i=i+1)

a<=a+data_in[i];

end

assign weight_out=a;

endmodule

but , this logic is not right.and a combinational loop occurs.

any convenient and right method?

thank you!

2 Replies

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    Hi,

    I don't know Verilog

    In VHDL, you can use "variable" for counters

    you can use "function" or "procedure" to find out the number of '1'. This function will be something like

    for(i=0;i<IN_WIDTH;i=i+1)
    a<=a+data_in;
    end
  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    A nice way to do this is by writing a recursive function.

    You first extend the vector with '0's so that the number of bits is a nice binary boundary, in the case you give 2048. You then call the recursive function which calls itself for the two halves. This continues until we have just 2 bits left.

    This will generate a nice tier of adders with the shortest delay and if you code it carefully minimal logic resources.

    Unfortunately I don't know Verilog (yet, but I ordered my first book on it).

    In VHDL it would look (somewhat) like this:

    
    function number_of_bits( src : std_logic_vector) return natural is
    begin
    if (src'high = 0 ) then
    -- we're down to a single bit
    if (src(0) = '0') then
    return 0 ;
    else 
    return 1 ;
    end if ;else-- we can split
    return number_of_bits( upper_half(src) ) 
    + number_of_bits( lower_half(src) ) ;
    end if
    end function number_of_bits ;
    

    Opposed to what a C-program or so would do, the HDL compiler will unroll the recursive loop into a nice tier of consecutive adders, in this case 11 layers and 2047 in total.