bit-manipulationvhdlfpga

Is there any short-way to find first '1' bit?


I want to show ,the mentioned problem on the title, to you in a function.

finding_first_one(signal a : std_logic_vector(...)) { return bit_number }

Meaning this, lets say, we have a signal '10010100', then return value, bit_number, should be 2. Is there any short way to find it in one cycle. I do not want to scan all the bits per clock.


Solution

  • You can do a for loop in your function.
    Be aware that for loop cannot always be implemented on hardware and that it can use A LOT of logic elements.
    Try something like this (not tested). index should be equal to 2 in one clock cycle.

    architecture behav of test is
    
      signal sig    : std_logic_vector(15 downto 0) := x"2224";
      signal index  : integer;
    
      function finding_first_one (signal a : std_logic_vector()) return integer is
      begin    
        for i in a'low to a'high loop
          if a(i) = '1' then
            return i;
          end if;
        end loop;    
        -- all zero
        return -1;
      end function;
    
    begin
    
      process (CLK)
      begin
        if rising_edge(clk) then
          index <= finding_first_one(sig);
        end if;
      end process;
    
    end architecture;