To answer the questions in the comments:
... but did you mean that I should use the package STD_LOGIC_SIGNED?
I just wondering if the compiler is 'smart' enough to recognize the sign of each number?
The compiler is smart enough if you use the correct data-types. A std_logic_vector
is just an array (vector) of std_logic
values (bits).
This vector has no sign. If you use signed
instead of std_logic_vector
, the compiler knows that it is treating signed numbers.
Do not use the std_logic_arith
and std_logic_signed
packages from Synopsys. They have been super-seeded by the now VHDL Standard package numeric_std
. This package defines the data type signed
alongside with relational operators like <
, <=
, =
, /=
, >
, >=
. Both operands in the comparison can be of different length, the shorter operand will be sign-extended first.
You can convert from std_logic_vector
to signed
with:
signal x : std_logic_vector(7 downto 0); -- 8 bit for example
signal y : signed(7 downto 0);
y <= signed(x);
and back
signal y : signed(7 downto 0);
signal z : std_logic_vector(7 downto 0); -- 8 bit for example
z <= std_logic_vector(y);
Of course, you can also use variables instead of signals (using the :=
assignment).
For example, to find the maximum value in an array of signed numbers, you can do:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity maximum_finder is
end maximum_finder;
architecture behavioral of maximum_finder is
type array_of_signed is array(natural range <>) of signed(3 downto 0);
signal signed_numbers : array_of_signed(0 to 2) :=
( 0 => "0000", -- 0
1 => "0001", -- 1
2 => "1111"); -- -1
signal maximum : signed(3 downto 0);
begin -- behavioral
process(signed_numbers)
variable tmp : signed(3 downto 0);
begin
tmp := "1000"; -- smallest number = -8
for i in signed_numbers'range loop
if signed_numbers(i) > tmp then
tmp := signed_numbers(i);
end if;
end loop; -- i
maximum <= tmp;
end process;
end behavioral;
Of course, this does not actually solve your homework. You have to adapt it, to avoid plagiarism.
numeric_std
provides a data typesigned
for calculations on signed binary numbers. \$\endgroup\$