Electronic – Making a simple 4 bit adder into a 4 bit adder with carry in & out

addervhdl

I have coded a simple signed 4 bit adder. It doesn't have any carry in or carry out so it easily overflows.
Below you can see my code.

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity four_bit_adder_simple is
        port(
                A, B : in std_logic_vector(3 downto 0);
                Sum : out std_logic_vector(3 downto 0));
end four_bit_adder_simple;

architecture signed_impl of four_bit_adder_simple is
begin
        sum <= std_logic_vector(signed(A) + signed(B));
end signed_impl;

Port mapping:

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity four_bit_adder_tester is
    port(
            SW : in std_logic_vector(7 downto 0);
            LEDR : out std_logic_vector(3 downto 0));
end four_bit_adder_tester;

architecture tester_impl of four_bit_adder_tester is

begin

i1: entity work.four_bit_adder_simple(signed_impl)
    port map(
    A => SW(3 downto 0),
    B => SW(7 downto 4),
    Sum => LEDR(3 downto 0)
    );
end architecture;

How can I add a carry-in and a carry-out by using the resize function to change the bit size of the vectors before adding them together?

Best Answer

You don't need the resize function. Just create an internal signal of the correct length, and concatenate 0's to your inputs. Such as:

library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;

entity four_bit_adder_simple is
    Port ( a    : in  std_logic_vector(3 downto 0);
           b    : in  std_logic_vector(3 downto 0);
           cin  : in  std_logic;
           sum  : out std_logic_vector (3 downto 0);
           cout : out std_logic );
end four_bit_adder_simple;

architecture Behavioral of four_bit_adder_simple is
    signal total : std_logic_vector(4 downto 0);
begin

    total <= ('0'&a) + ('0'&b) + cin;
    sum   <= total(3 downto 0);
    cout  <= total(4);

end Behavioral;


edit


In hindsight, using the non-standard std_logic_unsigned is not the best approach (When to use VHDL library std_logic_unsigned and numeric_std?).

See my answer here instead.

Related Topic