Search code examples
vhdlhdl

Sorting a vector in VHDL


I was trying to sort a vector for example if the input is 101010 the output would be 111000. Every time when I am trying to simulate the code, my output is always all zeros.

I am posting my code for your reference. If I am missing something or if there is any better way to implement this please let me know

    library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity num_ones_for is
    Port ( A : in  STD_LOGIC_VECTOR (15 downto 0);
           A_S : out  STD_LOGIC_VECTOR (15 downto 0));
end num_ones_for;

architecture Behavioral of num_ones_for is
function sort_binary ( ones :unsigned;a : std_logic_vector) return std_logic_vector is
    variable A1: std_logic_vector ( 15 downto 0) := (others =>'0') ;
    begin
    for i in 15 to(15 - to_integer(ones)) loop
     A1(i) := '1';
    end loop;
    return A1;
    end function sort_binary;
signal ones : unsigned (4 downto 0);
begin

process(A)
variable count : unsigned(4 downto 0) := "00000";
begin

count := "00000";   --initialize count variable.
    for i in 0 to 15 loop   --for all the bits.
        count := count + ("0000" & A(i));   --Add the bit to the count.
    end loop;
    ones <= count;    --assign the count to output.
end process;
A_S <= sort_binary(ones =>ones,a =>A);

end Behavioral;

enter image description here


Solution

  • At last, I resolved most of the errors and changed the logic of the code a bit. If anyone wants to code the same type of VHDL code in the future, could refer to my code. If there is any better way to do solve this please let me know always happy to learn. Thanks

    library IEEE;
    use IEEE.STD_LOGIC_1164.ALL;
    use IEEE.NUMERIC_STD.ALL;
    
    entity num_ones_for is
        Port ( A : in  STD_LOGIC_VECTOR (15 downto 0);
               A_S : out  STD_LOGIC_VECTOR (15 downto 0));
    end num_ones_for;
    
    architecture Behavioral of num_ones_for is
    function sort_binary ( ones :unsigned;a : std_logic_vector) return std_logic_vector is
        variable A1: std_logic_vector ( 15 downto 0) := (others =>'0') ;
        begin
        for i in 0 to 15 loop
        if i >(15- ones) then
         A1(i) := '1';
         else
         next;
         end if;
        end loop;
        return A1;
        end function sort_binary;
    signal ones : unsigned (4 downto 0);
    begin
    
    process(A)
    variable count : unsigned(4 downto 0);
    begin
    
    count := "00000";   --initialize count variable.
        for i in 0 to 15 loop   --for all the bits.
            count := count + ("0000" & A(i));   --Add the bit to the count.
        end loop;
        ones <= count;    --assign the count to output.
    end process;
    A_S <= sort_binary(ones =>ones,a =>A);
    
    end Behavioral;
    

    enter image description here