Forum Discussion
Altera_Forum
Honored Contributor
15 years agoA 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.