Search code examples
vhdl

Variable length std_logic_vector initialization in VHDL


I have a variable length vector std_logic_vector(X downto 0). Now I'm trying to define a constant in my package for reset, such that the lower X/2 bits are ones, and the others zero.

For example, a 3 bit vector (X=3) would make the constant "011" and a 4 bit vector would give the constant "0011".

How can I do this in a VHDL package? The code below explains what I am trying to do.

type Entry_Type is record
  state : std_logic_vector(X-1 downto 0);
end record;
constant Entry_Constant : Entry_Type := <???>;

Solution

  • There are at least two choices to initialize your record type as you want. One is using an initialization function, and the other is using the value of N in an aggregate.

    Functions are a nice way to initialize custom data types. In your case, you could create a function default_entry_from_width(n), returning an entry_type value:

    type entry_type is record
        state: std_logic_vector;
    end record;
    
    function default_entry_from_width(width: natural) return entry_type is
        variable return_vector: std_logic_vector(width-1 downto 0);
    begin
        for i in return_vector'range loop
            return_vector(i) := '1' when i <= width/2 else '0';
        end loop;
        return (state => return_vector);
    end;
    
    constant ENTRY_1: entry_type := default_entry_from_width(3);  -- return 011
    constant ENTRY_2: entry_type := default_entry_from_width(4);  -- return 0011
    

    The other alternative is to initialize the constant with an aggregate, using the previsouly defined value of N:

    constant N: natural := 4;
    constant ENTRY_3: entry_type := (
        state => (
            N-1 downto N/2 => '1',
            N/2-1 downto 0 => '0'
        )
    );