SLP
SLP

Reputation: 305

How to calculate the number of bits needed for an std_logic_vector when its size is parametrable?

I have an entity that instanciates a FIFO which depth is a generic:

DEPTH_FIFO : natural range 2 to 64 := 3; -- number of vectors in the FIFO

I have to declare a counter that could store the index of the FIFO but I need to know which size has to be the counter.

signal cnt_FIFO : unsigned(length_cnt_FIFO-1 downto 0);

My problem is to find a way to calculate the constant length_cnt_FIFO.

I have tried this :

constant length_cnt_FIFO : natural := CEIL(LOG(2, DEPTH_FIFO));

with the library use ieee.MATH_REAL.all;

but I get problems of type conversion.

Anyone has an idea to make this work, or any other solution ?

Thanks in advance,

SLP

Upvotes: 2

Views: 1514

Answers (2)

Isaac Goss
Isaac Goss

Reputation: 31

I have the following function defined in a utility package I keep handy:

function ilog2(val : integer) return integer
is
    constant vec : std_logic_vector(31 downto 0) :=
        std_logic_vector(to_unsigned(val, 32));
begin
    for i in vec'left downto vec'right loop
        if (vec(i) = '1') then
            return i;
        end if;
    end loop;
    return -1; -- The number is '0'.
end function ilog2;

Upvotes: 2

am9417
am9417

Reputation: 1036

  1. Your DEPTH_FIFO is natural, but you have to convert it to a Real to pass it to the logarithmic function.
  2. The CEIL function returns a real: you have to convert it back to a natural to store it in a constant of natural type.
  3. The parameters of LOG function are real, so passing a literal 2 causes problems because it is handled as an integer. Use e.g. 2.0 instead or the LOG2 function.

This did the trick for me:

constant length_cnt_FIFO : natural := natural(CEIL(LOG2(real(DEPTH_FIFO))));

Upvotes: 4

Related Questions