On Dec 5, 4:28*am, Tricky <trickyh...@gmail.com> wrote:
> If you have a copy of modelsim with the unisim libraries, see if you
> can view the source code here. It is Xilinx Proprietary so you may not
> have the source.
> As for log2, its a fairly universal function you can write easily with
> a for loop:
>
> function log2( i : natural) return integer is
> * variable temp * *: integer := i;
> * variable ret_val : integer := 1; --log2 of 0 should equal 1 because
> you still need 1 bit to represent 0
> begin
> * while temp > 1 loop
> * * ret_val := ret_val + 1;
> * * temp * *:= temp / 2;
> * end loop;
>
> * return ret_val;
> end function;- Hide quoted text -
>
> - Show quoted text -
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