Practical VHDL functions from std_logic_1164, numeric_std, std.env, textio and math_real.
Standard packages provide conversions, numeric operations and testing tools. Choose them for the data type and context: RTL calculation, elaboration or simulation.
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
Use numeric_std for vector arithmetic. Legacy packages std_logic_arith, std_logic_unsigned and std_logic_signed are not IEEE-standard packages.
Read levels and edges
std_logic_1164 defines nine-state logic types and associated functions:
Function
Use
rising_edge(i_clk)
Detect a rising clock edge
falling_edge(i_clk)
Detect a falling edge
Is_X(w_bus)
Detect an unknown value ('U', 'X', etc.)
To_01(w_bus)
Map a vector back to 0/1 values
to_hstring(w_bus)
Print a vector in hexadecimal during simulation
Use rising_edge for a rising-edge register:
p_reg : process(i_clk)begin if rising_edge(i_clk) then if i_rst = '1' then r_count <= (others => '0'); else r_count <= r_count + 1; end if; end if;end process p_reg;
It recognizes transitions between valid low and high std_logic levels, including weak levels. A simple i_clk'event and i_clk = '1' can also accept a transition from an unknown state.
In a testbench, Is_X detects unknown values before accepting a result:
assert not Is_X(o_data) report "o_data contains an unknown value: " & to_hstring(o_data) severity error;
This checks the simulation model rather than physically measuring an X state.
Convert and calculate with numeric_std
Function
Use
to_unsigned(i, n)
Convert a natural integer to unsigned(n-1 downto 0)
to_signed(i, n)
Convert a signed integer to signed(n-1 downto 0)
to_integer(x)
Convert unsigned or signed to integer
resize(x, n)
Adapt the width of an unsigned or signed value
shift_left(x, n)
Shift left
shift_right(x, n)
Shift right
rotate_left(x, n)
Rotate left
rotate_right(x, n)
Rotate right
Conversions to a bus specify width explicitly:
signal r_count : unsigned(7 downto 0);signal w_index : integer range 0 to 255;w_index <= to_integer(r_count);r_count <= to_unsigned(42, r_count'length);
resize extends an unsigned with zeros and a signed with its sign. To retain an addition's carry, widen operands before calculating:
Use these statements in the appropriate testbench regions with the required packages and VHDL version.
Prepare simulation calculations
math_real includes sqrt, ceil, floor, sin, cos and uniform. It supports testbenches and elaboration-time constants; these calls on real values generally do not describe runtime hardware calculations.
uniform generates pseudo-random stimuli from two seeds: