Global training solutions for engineers creating the world's electronics

One Hot to Binary Encoder

This function will take a one hot binary vector and encode it into binary. If the left most bit of the one hot input is set, the output is zero. 


The function should synthesise to the minimum number of OR gates required to convert one hot to binary.


The function uses unconstrained parameters so it can be reused for a binary vector of any size (n) and a one-hot vector of size 2**n.

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

entity onehot_binary is
  port    ( onehot_in  : in  std_logic_vector;
            binary_out : out std_logic_vector  );
    assert 2**binary_out'length = onehot_in'length severity failure;


architecture rtl of onehot_binary is

  function one_hot_to_binary (
    One_Hot : std_logic_vector ;
    size    : natural
  ) return std_logic_vector is

    variable Bin_Vec_Var : std_logic_vector(size-1 downto 0);


    Bin_Vec_Var := (others => '0');

    for I in One_Hot'range loop
      if One_Hot(I) = '1' then
        Bin_Vec_Var := Bin_Vec_Var or std_logic_vector(to_unsigned(I,size));
      end if;
    end loop;
    return Bin_Vec_Var;
  end function;


  binary_out <= one_hot_to_binary(onehot_in, binary_out'length);


How It Works:

The basic idea is simple - when a '1' is found in the onehot vector, the number corresponding to its bit position is placed into the binary output vector. Note that if the input vector is not one hot, the output will be the ORed bit positions of all set bits.


To download the VHDL source code for this model, click here.

Back to VHDL models.

Great training!! Excellent Instructor, Excellent facility ...Met all my expectations.
Henry Hastings
Lockheed Martin

View more references