DarkPassenger
DarkPassenger

Reputation: 67

two's complement binary VHDL

I have to transfer a binary number from A to -A in VHDL. I have some questions about two's complement notation. For instance if I have A(8 bit) = 5, in binary 0000 0101. From online sources I realized that to translate it into two's complement negative form, I need to invert all bits adding 1 at the end:

0000 0101 --> 1111 1010 + 0000 0001 = 1111 1011 and this represents -A=-5;

My doubts now is about this final binary form that can represent -5 and 251, how can I recognize if it is -5 or 251?

By the way, this method is not so simply to be described in VHDL. Do you know if there is any simpler method?

Upvotes: 0

Views: 3214

Answers (1)

JHBonarius
JHBonarius

Reputation: 11261

Intuitively my reasoning would be: you are using two's complement, which is a signed number representation, therefore negative values exist. If negative values exist, you need a sign bit. That will leave 7-bits for the magnitude: hence you can only represent a value between -128 and 127. Value 251 is not within this range: It cannot be represented using 8-bits two's complement notation. Thus only -5 is valid.

The easiest way to realize two's complement sign inversion in VHDL is using the numeric_bit package.

library ieee;
entity bit_inv is
    generic(width : positive);
    port(
        A     : in  bit_vector(width-1 downto 0);
        A_inv : out bit_vector(width-1 downto 0));
end entity;

architecture rtl of bit_inv is
    use ieee.numeric_bit.all;
begin
    A_inv <= bit_vector(-signed(A));
end architecture;

entity bit_inv_tb is end entity;

library ieee;
architecture beh of bit_inv_tb is
    use ieee.numeric_bit.all;
    constant width : positive := 8;
    signal A, A_inv : bit_vector(width-1 downto 0);
begin
    DUT : entity work.bit_inv
        generic map(width => width)
        port map(A=>A, A_inv =>A_inv);

    test: process begin
        A <= bit_vector(to_signed(5,width));
        wait for 1 ns;
        assert to_integer(signed(A_inv)) = -5 report "A_inv is not equal to -5" severity failure;
        wait;
    end process;
end architecture;

Upvotes: 1

Related Questions