Search This Blog

Sunday 6 October 2013

VHDL Code for 4-Bit Magnitude Comparator

Given below code is about 4-bit Magnitude comparator. First code is written using structural method and second code is written using behavioral method. This module has two 4-bit inputs 'a' and 'b' and three single bit output 'ag', bg' and 'eq'. In this code if 'a' is greater than 'b' then 'ag' will go high and rest will be low. Same way if 'b' is grater than 'a' then 'bg' will go high and rest will go low. If 'a' and 'b' are equal then 'eq' will go high and rest will go low. Find out Test Bench here.

  • Structural Method

library ieee;
use ieee.std_logic_1164.all;

entity mag_comp_4b is

  port (
    a, b : in  std_logic_vector(3 downto 0);       -- inputs
    ag, bg, eq : out std_logic);      -- ag if a > b, bg if b > a, eq if a=b

end mag_comp_4b;

architecture structural of mag_comp_4b is
signal s : std_logic_vector(3 downto 0);         -- intermediate signal
begin 

s(0)<= a(0) xnor b(0);
s(1)<= a(1) xnor b(1);
s(2)<= a(2) xnor b(2);
s(3)<= a(3) xnor b(3);

eq<=s(3) and s(2) and s(1) and s(0);

ag<=(a(3) and (not b(3))) or
    (s(3) and a(2) and (not b(2))) or
    (s(3) and s(2) and a(1)and (not b(1))) or
    (s(3) and s(2) and s(1) and a(0) and (not b(0)));

bg<=(b(3) and (not a(3))) or
    (s(3) and b(2) and (not a(2)))or
    (s(3) and s(2) and b(1)and (not a(1))) or
    (s(3) and s(2) and s(1) and b(0) and (not a(0)));

end structural;


Above code is synthesized by Xilinx Vivado. RTL view of Magnitude Comparator is given below
RTL View of Magnitude Comparator (Structural)

  • Behavioral Method

library ieee;
use ieee.std_logic_1164.all;

entity mag_comp_4b is
  port (
    a, b       : in  std_logic_vector(3 downto 0);       -- inputs
    ag, bg, eq : out std_logic);                         -- ag if a > b, bg if b > a, eq if a=b

end mag_comp_4b;

architecture behav of mag_comp_4b is

begin
 process (a,b)
  begin
   if (a > b) then
    ag <= '1';
    bg <= '0';
    eq <= '0';
   elsif (b > a) then
    ag <= '0';
    bg <= '1';
    eq <= '0';
   else
    ag <= '0';
    bg <= '0';
    eq <= '1';
   end if;
  end process;
end behav;

This code is synthesized by Xilinx Vivado. RTL view of Magnitude Comparator(Behavioral) is given below
RTL view of Magnitude Comparator(Behavioral)

1 comment:

  1. ℍ𝕖𝕣𝕖 𝕚𝕤 𝕘𝕠𝕠𝕕 𝕒𝕟𝕕 𝕦𝕟𝕕𝕖𝕣𝕤𝕥𝕒𝕟𝕕𝕚𝕟𝕘 𝕔𝕠𝕕𝕚𝕟𝕘 𝕠𝕗 𝕧𝕙𝕕𝕝

    ReplyDelete