Home > VHDL > Arithmetic Circuits > Adder Subtractor

4 Bit Adder-Subtractor :

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
		
entity addsub is
          generic (NBITS: natural := 4);
              port  ( clk, rst, add: in std_logic;
                         a, b : in unsigned(NBITS-1 downto 0);
                         z : out unsigned(NBITS-1 downto 0));
end addsub;

architecture behav of addsub is
signal a_reg, b_reg, z_reg: unsigned(NBITS-1 downto 0);
begin
      process (rst, clk)
           begin
               if   rst = '1' then
                    a_reg <= (others => '0');
                    b_reg <= (others => '0');
  	      z <= (others => '0');
               elsif clk''event and clk = '1' then
                    a_reg <= a;
                    b_reg <= b;
                    z <= z_reg;
               end if;
      end process;
    z_reg <= a_reg + b_reg when add = '1' else
    a_reg - b_reg;
end behav;