Search code examples
vhdl

How do I find the array index with its highest value with vhdl?


I would like to find the array index with its highest value. Is it possible to simply use an vhdl-attribute therefore? If so, how?

TYPE x_Array IS ARRAY (0 TO 3) OF STD_LOGIC_VECTOR(2 DOWNTO 0);      
SIGNAL y : x_Array;

Example:

x_Array(0) = "000"
x_Array(1) = "011"
x_Array(2) = "111"
x_Array(3) = "101"


index <= x_Array'high;    -- is this correct or..?

Question: How can I get the index of 2 (x_Array(2) has the highest value (7)) in vhdl?


Solution

  • As written, your question doesn't make sense: a std_logic_vector needs an interpretation to even be considered as a number.

    So let's assume you knew that and wrote the sensible

    library ieee;
    use ieee.numeric_std.all;
    use ieee.std_logic_1164.all;
    type x_array is array(integer range <>) of unsigned(2 downto 0);      
    signal y : x_array(0 to 3);
    

    just write the function

    function maxindex(a : x_array) return integer is
      variable index : integer := 0;
      unsigned foundmax : unsigned(2 downto 0) := (others => '0');
    begin
      for i in 0 to a'high loop
        if a(i) > foundmax then
          index := i;
          foundmax := a(i);
        end if;
      end loop
      return index;
    end function;
    

    And apply as necessary.