Search code examples
vhdl

How to determine direction of a vector in VHDL (downto vs to)?


I need to write a function that will shift data into an input vector. The input could be of type signed or unsigned. In order to make the function robust, I need to know the direction of the input vector i.e range declared using downto vs to. This information will be used to determine what index has the least significant bit.

How do I find out how the range has been declared and choose the correct least significant and most significant bit based on that information?


Solution

  • Array types have the default attributes 'ascending and 'descending which are both functions that return true/false depending on whether the range is actually to (ascending) or downto (descending). Hence, you will likely need to have the following coding style if you explicitly need to investigate the direction:

    if p'ascending then
      -- do code for to direction
    else
      -- do code for downto direction
    end if;
    

    Alternatively, you can use an alias to "normalise" the direction inside the function, which means an if/else is not needed depending on direction, as you know the direction inside the function:

    function do_something( p : bit_vector ) return bit_vector is
      alias p_a  : bit_vector(p'length-1 downto 0) is p;    -- normalise p
      variable r : p_a'subtype;
    begin
       -- use p_a as a downto vector
       
       return r;
    end function;