I have been trying to design an 8 bit ALU, but i had trouble with overflow and Cout. I spent hours trying to do it but with no correct result, I hope that someone explain how to correct it. thanks a lot.
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;
-- Uncomment the following library declaration if instantiating
-- any Xilinx primitives in this code.
--library UNISIM;
--use UNISIM.VComponents.all;
entity ALU_8_bit is
Port ( A : in STD_LOGIC_VECTOR (3 downto 0);
B : in STD_LOGIC_VECTOR (3 downto 0);
CTRL : in STD_LOGIC_VECTOR (2 downto 0);
Y : out STD_LOGIC_VECTOR (3 downto 0);
OFL: out STD_LOGIC;
COUT: out STD_LOGIC
);
end ALU_8_bit;
architecture Behavioral of ALU_8_bit is
signal result: std_logic_vector(3 downto 0);
begin
process(A,B,CTRL) begin
if (CTRL ="000") then
result <= A;
elsif (CTRL = "001") then
result <= A + B;
elsif (CTRL = "010") then
result <= A - B;
elsif (CTRL = "011") then
result <= NOT A + 1;
elsif (CTRL = "100") then
result <= NOT A;
elsif (CTRL = "101") then
result <= A AND B;
elsif (CTRL = "110") then
result <= A OR B;
else --(CTRL = "111") then
result <= A XOR B;
end if;
end process;
Y <= result;
--process (A,B,result,cout)
--begin
-- if ((A(3) = '1') and (B(3) ='1') and (result(3) = '0')) then Cout <= '1';
-- elsif ((A(3) = '1') and (B(3) = '0') and (result(3) = '0')) then Cout <= '1';
-- elsif ((A(3) = '0') and (B(3) = '1') and (result(3) = '0')) then Cout <= '1';
-- else Cout <= '0';
-- end if;
--end process;
process(result,CTRL)
begin
if (CTRL = "001") then
--Y <= result;
COUT <= A(3) and B(3); --result(3);
OFL <= result(3) xor (B(2) and A(2));
else
OFL <= '0';
COUT <= '0';
end if;
end process;
end Behavioral;
COUT
is assignedresult(4)
. Also note theOFL
case needs to be specified for both add and subtract (and correctly) see Calculating Overflow Flag: Method 1 (read the whole thing). You'd continue to useA(3)
,B(3)
andresult(3)
bits). Note that in reality A - B is A + not B + 1, where the + 1 represents the carry in. You're counting on synthesis to make only one ALU. If you had carry in you could use Method 2.