This really should not be called log2() because it does not return the

base 2 logarithm of the argument. It returns log2(i) + 1 instead. For

example, log2(1) = 0, log2(2) = 1 and log2(0) is undefined.

-- this (untested) function returns the base 2 logarithm of n

n>= 1)

function log2(n : positive) return natural is

variable temp : positive := n;

variable retval : natural := 0;

begin

while temp> 1 loop

retval := retval + 1;

temp := temp / 2;

end loop;

return retval;

end function log2;

I don't know if Xilinx's unisim log2() is similarly mathematically

flawed, but I wanted to make sure that someone googling for a

mathematical function "vhdl log2()" is not mislead. You can probably

tell from the context of how Xilinx uses it whether or not their's is

mathematically accurate, or just logically convenient.

When calculating the number of bits required to represent the range 0

to n, use log2(n) + 1. However, the upper index of an appropriately

sized unsigned subtype would be log2(n), assuming the lower index is

0.

subtype n_range is natural range 0 to n;

subtype n_unsigned is unsigned(log2(n_range'high) downto 0);

variable x : natural range 0 to 0; -- is a constant

Andy