The twos complement of a number can be generated by examinin
The two\'s complement of a number can be generated by examining the binary representation from right (LSB) to left (MSB). Note the position of the first \'1\' when scanning from right to left and then complement (invert) all bits to the left of that first \'1 \'. For example, the two\'s complement of decimal 6 (0110) is (1010) which is -6 in 4-bit, two\'s complement notation. Construct a VHDL behavioral model (using a process and variables) of a module that takes as input, an 8-bit word din and a single bit clk. On the rising edge of clk, the module reads the 8-bit number din and negates its value (using the algorithm described above) to produce an 8-bit output dout. Use std_Iogic and std_logic_vector for your input and output data types. Enter your code into the simulator and test the result for a number of different positive and negative values of din. Show your code and the test waveforms. Set the simulator output to display din and dout in signed decimal format.
Solution
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
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 two_comp_gen is
Port ( din : in STD_LOGIC_VECTOR (7 downto 0);
clk : in STD_LOGIC;
dout : out STD_LOGIC_VECTOR (7 downto 0));
end two_comp_gen;
architecture Behavioral of two_comp_gen is
begin
process(clk)
variable i : natural := 7;
begin
if(clk=\'1\' and clk\'EVENT) then
L1:while i>=0 loop
if (din(i)=\'1\')then
dout(i)<=not din(i);
dout(i-1 downto 0)<= din(i-1 downto 0);
i:=0;
else
dout(i)<=not din(i);
i:=i-1;
end if;
end loop L1;
end if;
end process;
end Behavioral;
