比如BCD碼q(11 downto 0)可以表示0到999,前四位是個位,中四位是十位,後四位是百位。不知道對於溢出的有什麽要求,我設成溢出後不做任何運算。
library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;
entity add_sub is
port(
clk : in std_logic;
clr : in std_logic;
sl : in std_logic;
q : out std_logic_vector(11 downto 0));
end add_sub;
architecture add_sub_arc of add_sub is
signal cnt : std_logic_vector(11 downto 0);
begin
process(clk,clr,cnt)
begin
if clr = '0' then
cnt <= (others => '0');
elsif clk = '1' and clk'event then
if sl = '0' then -- adder
if cnt /= "100110011001" then
if cnt(3 downto 0) = "1001" then
cnt(3 downto 0) <= (others => '0'); -- units
cnt(7 downto 4) <= cnt(7 downto 4) + '1'; -- tens
else
cnt(3 downto 0) <= cnt(3 downto 0) + '1'; -- units
end if;
if cnt(7 downto 4) = "1001" then -- tens
cnt(7 downto 4) <= (others => '0'); -- tens
cnt(11 downto 8) <= cnt(11 downto 8) + '1'; -- hundreds
end if;
else
cnt <= cnt;
end if;
else -- substractor
if cnt /= "000000000000" then
if cnt(3 downto 0) = "0000" then
cnt(3 downto 0) <= "1001";
cnt(7 downto 4) <= cnt (7 downto 4) - '1';
else
cnt(3 downto 0) <= cnt (3 downto 0) - '1';
end if;
if cnt(7 downto 4) = "0000" then
cnt(7 downto 4) <= "1001";
cnt(11 downto 8) <= cnt (11 downto 8) - '1';
end if;
end if;
end if;
q <= cnt;
end if;
end process;
end add_sub_arc;