如何在不使用 for 循环的情况下获取 one-hot 编码向量的索引?

How can I get the index of a one-hot encoded vector without using a for-loop?

我有一个信号 "event_id",其中任何时候只有一个位为高。我需要将这个单热编码信号转换为索引的整数值。

信号:

signal event_id: std_logic_vector(3 downto 0);
signal event_index: natural;

我知道我可以用 for 循环来做到这一点。这就是我目前正在做的事情:

for i in 3 downto 0 loop
    if(event_id(i) = '1') then
      event_index = i;
    end if;
end loop;

是否有不需要 for 循环或单独遍历每一位的更好方法来执行此操作?我知道我可以用 for-loop 方法创建一个函数,但我觉得应该有一个我缺少的简单解决方案。

VHDL中没有"simple"生成one-hot vector索引的方案。

对于一个 4 位的单热向量,因此得到 2 位的索引,你所做的循环是一个 OK 的解决方案,它是可读的并且在实现中不会占用太多资源。虽然它不是最小的解决方案,因为它不允许实现大小从单热 属性 中受益,因为它 returns 设置位的最低索引。对于短的单热向量,如果在 FPGA 中实现,这并不重要,因为它使用量化的 LUT 资源。

对于较长的单热向量,如果使用单热 属性,实现会更小。这可以通过一种算法来完成,其中索引位是从 one-hot 向量和掩码生成的。下面显示了一个函数。

-- One hot to index calculate; assuming LEN_HOT = 2 ** LEN_IDX
function hot2idx_cal(hot : std_logic_vector) return std_logic_vector is
  variable mask_v : std_logic_vector(LEN_HOT - 1 downto 0);
  variable res_v  : std_logic_vector(LEN_IDX - 1 downto 0);
begin
  for i in 0 to LEN_IDX - 1 loop
    -- Generate mask
    for j in 0 to LEN_HOT - 1 loop
      if ((j / (2 ** i)) mod 2) = 0 then
        mask_v(j) := '0';
      else
        mask_v(j) := '1';
      end if;
    end loop;
    -- Apply mask and generate bit in index
    if unsigned(hot and mask_v) = 0 then
      res_v(i) := '0';
    else
      res_v(i) := '1';
    end if;
  end loop;
  return res_v;
end function;

提供 Minimal, Complete and Verifiable example 以便演示解决方案。

对于长度为 4 的全局静态单热向量数组,逻辑是两个或门:

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity onehot2indx is
end entity;

architecture foo of onehot2indx is
    signal event_id:    std_logic_vector(3 downto 0) := "1000";
    signal event_index: natural;
begin
    event_index <= to_integer (
        unsigned'((event_id(3) or event_id(2)) & (event_id(3) or event_id(1)))
    );

STIMULUS:
    process
    begin
        for i in 0 to 3 loop
            wait for 10 ns;
            event_id <= (others => '0');
            event_id(i) <= '1';
        end loop;
        wait for 10 ns;
        wait;
    end process;
end architecture;

产生:

考虑硬件描述而不是语言问题。

对于一个太乏味以至于无法轻易看出真相的热门向量长度 table 输入和输出可以用作逻辑简化软件(例如 espresso)的输入以及依赖于循环语句或案例语句在合成软件上。

长度4是琐碎的,容易看出没有道理table。

(有一次你不得不为算术函数合成支付许可证费用,便宜让你想到了逻辑,请注意 Morten 如何引用结果索引值长度,尽管在使用自然时依赖于合成映射和缩减.)