library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.std_logic_arith.all;

entity fpencr is
    port (
        B: in STD_LOGIC_VECTOR(10 downto 0); -- fixed-point number
        M: out STD_LOGIC_VECTOR(3 downto 0); -- floating-point mantissa
        E: out STD_LOGIC_VECTOR(2 downto 0)  -- floating-point exponent
    );
end fpencr;

architecture fpencr_arch of fpencr is
function round (BSLICE: STD_LOGIC_VECTOR(4 downto 0))
    return STD_LOGIC_VECTOR is
  variable BSU: UNSIGNED(3 downto 0);
  begin
    if BSLICE(0) = '0' then return BSLICE(4 downto 1);
    else null;
      BSU := UNSIGNED(BSLICE(4 downto 1)) + 1;
      return STD_LOGIC_VECTOR(BSU);
    end if;
  end;
begin
  process(B)
  variable BU: UNSIGNED(10 downto 0);
  begin
    BU := UNSIGNED(B);
    if    BU < 16      then M <= B( 3 downto 0); E <= "000";
    elsif BU < 32-1    then M <= round(B( 4 downto 0)); E <= "001";
    elsif BU < 64-2    then M <= round(B( 5 downto 1)); E <= "010";
    elsif BU < 128-4   then M <= round(B( 6 downto 2)); E <= "011";
    elsif BU < 256-8   then M <= round(B( 7 downto 3)); E <= "100";
    elsif BU < 512-16  then M <= round(B( 8 downto 4)); E <= "101";
    elsif BU < 1024-32 then M <= round(B( 9 downto 5)); E <= "110";
    elsif BU < 2048-64 then M <= round(B(10 downto 6)); E <= "111";
    else                    M <= "1111";                E <= "111";
    end if;
  end process;
end fpencr_arch;
