How can I build if sentence with compare to variou

2019-06-26 01:22发布

问题:

How can i write this if statement condition in better way?

if ((data_in(8 downto 1)=x"70") or (data_in(8 downto 1)=x"69") or 
    (data_in(8 downto 1)=x"72") or (data_in(8 downto 1)=x"7A") or
    (data_in(8 downto 1)=x"6B") or (data_in(8 downto 1)=x"73") or
    (data_in(8 downto 1)=x"74") or (data_in(8 downto 1)=x"6C") or
    (data_in(8 downto 1)=x"75") or (data_in(8 downto 1)=x"7D")) then
      data_make_code <= data_in (8 downto 1); -- enter key to buffer
      wrong_data <='0';
      cnt_bit :=0;
      -- if valid key then
      current_state <= break_code_receive; 
elsif
 ...
end if;

回答1:

A case statement can be used to compare with multiple values, and the others part of the case can then be used as "else", like:

case data_in(8 downto 1) is
  when x"70" | x"69" | x"72" | x"7A" | x"6B" |
       x"73" | x"74" | x"6C" | x"75" | x"7D" =>
    ...  -- if part of code
  when others =>
    ...  -- else part of code
end case;

An alternative method is to use an array of std_logic_vector with the values, and then make a function that can determine if the data_in value equals either of the values in the array. The type and function declarations can then either be in the architecture or process declaration section. The code in VHDL-2008 can then look like:

type slv_array is array (natural range <>) of std_logic_vector;

function in_array(val : std_logic_vector; set : slv_array) return boolean is
begin
  for idx in set'range loop
    if val = set(idx) then
      return TRUE;
    end if;
  end loop;
  return FALSE;
end function;

...

if in_array(data_in, (x"70", x"69", x"72", x"7A", x"6B", 
                      x"73", x"74", x"6C", x"75", x"7D")) then
  ...  -- if part of code
else
  ...  -- else part of code
end if;

The alternative method requires a few declarations, but is more general applicable.