Search code examples
vhdl

How can I check for carry-out while using unsigned vector subtraction?


I try to implement an architecture that has only an 8-bit adder-subtractor. But there is an issue I can't solve. When I use subtractor architecture, I need to calculate carry-out, but I couldn't.

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use ieee.numeric_std.all;

entity sub is
            port ( a  : in std_logic_vector(7 downto 0);
                   b  : in std_logic_vector(7 downto 0);
                   o  : out std_logic_vector(7 downto 0)
                );
end sub;

architecture Behavioral of sub is
  signal a2,b2 : unsigned (7 downto 0);
begin
            a2<=unsigned(a);
            b2<=unsigned(b);

            o<=std_logic_vector(a2-b2);
 end Behavioral;

Edit: I'm talking about "c1" and "c5" signals in the picture.


Solution

  • You need to extend both operands by one bit, so the carry out is collected in the MSB of the result. The result is decomposed into carry bit c and subtraction result o.

    library IEEE;
    use     IEEE.STD_LOGIC_1164.ALL;
    use     IEEE.numeric_std.all;
    
    entity sub is
      port (
        a  : in  std_logic_vector(7 downto 0);
        b  : in  std_logic_vector(7 downto 0);
        o  : out std_logic_vector(7 downto 0);
        c  : out std_logic
      );
    end entity;
    
    architecture rtl of sub is
    begin
      (c, o) <= std_logic_vector(unsigned('0' & a) - unsigned('0' & b));
    end architecture;
    

    Note: This is VHDL-2008 code.