在上一篇文章中我们讨论了二进制加法器的原理,在此我们给出二进制加法器的VHDL描述:
library IEEE;
use IEEE.std_logic_1164.all;
package std_logic_arith is
type unsigned is array (natural range<>) of std_logic;
type signed is array (natural range<>) of std_logic;
type builtin_subprogram : string;
function "+"(L: signed; R: signed) return signed;
attribute builtin_subprogram of
"+"[signed, signed return signed] : function is "stdarith_plus_sss"; --不知这句
--什么意思
end std_logic_arith;
package body std_logic_arith is
function plus(A,B: signed) return signed is
variable carry : std_ulogic;
variable BV, sum : signed(A'left downto 0);
begin
if (A(A'left) = 'X' or B(B'left) = 'X') then
sum := (others => 'X');
return (sum;
end if;
carry := '0';
BV := B;
for i in 0 to A'left loop
sum(i) := A(i) xor BV(i) xor carry;
carry := (A(i) and BV(i)) or ((A(i) or BV(i)) and carry);
end loop; --for...loop语句最终实现为具体的数字门电路结构
--所以当A,B位数很大时加法器的结构也就会变得很复杂
--然而,这是符合设计加法器的数字电路理论的
return sum;
end ;
function "+"(L: signed; R: signed) return std_logic_vector is
constant length : integer := max(L'length,R'length);
begin
return std_logic_vector(plus(conv_signed(L,length), conv_signed(R,length)));
end;
此二进制加法器设计摘自IEEE.STD_LOGIC_ARITH数据包,在定点数,浮点数加法设计中最终都会调用此加法器作为加法运算的核心。