title: Implementing Overflow Checking in 4-bit Adder/Subtractor (VHDL)
body: <p>I am rather new (3 weeks) to VHDL, and I am having a problem in my latest assignment, which involves implementing overflow checking in a simple 4-bit adder:</p>
  
  <pre><code>    library IEEE;
  use IEEE.STD_LOGIC_1164.ALL;
  use IEEE.STD_LOGIC_UNSIGNED.ALL;
  
  entity add_sub_4bit is
      Port ( a : in  STD_LOGIC_VECTOR(3 downto 0);
             b : inout  STD_LOGIC_VECTOR(3 downto 0);
                sel: in STD_LOGIC );
             --sum : inout  STD_LOGIC_VECTOR(3 downto 0) 
  end add_sub_4bit;
  
  architecture Behavioral of add_sub_4bit is
  signal localflow : STD_LOGIC;
  signal localsum : STD_LOGIC_VECTOR (3 downto 0);
  
  begin
      localsum &lt;= a + b when sel = '1'
      else
      a - b;
  process(a,b,localsum) begin
      if a(3) = '0' AND b(3) = '0' AND localsum(3) = '1' then
          localflow &lt;= '1'; 
      elsif  a(3) = '1' AND b(3) = '1' AND localsum(3) = '0' then
          localflow &lt;='1';
      else
          localflow &lt;='0';
      end if;
  end process;
  end Behavioral;
  </code></pre>
  
  <p>Now, the test cases are as such:
  A=5, B=-3, giving 0 to sel adds them, 1 subtracts.
  A=6, B=2, working much the same.</p>
  
  <p>Now, given that the numbers are signed, of course, they are two's complement numbers, so is the result. However, I can only detect overflow in a case of adding 6 (0110) and 2 (0010), giving out -8 (1000), which is obviously an overflow case in 4-bit. But, when doing 5 -(-3), the result is much the same, 1000, but since I have given numbers of two different signs, I cannot detect overflow using my method.</p>
  
  <p>My teacher has suggested that we change the sign of B depending on the value of sel - I tried something like making b &lt;= b+"1000" based on that but that didn't help, and I don't know of other ways, being very new to the language. What can I do to get a proper program? Thank you.</p>