Search code examples
vhdl

VHDL 4 Bit Comperator using 2 Bit Comperator


I'm having troubles to create a 4-Bit Comparator using 2-Bit greater than Comparator and 2-bit equality Comparator.

greater than Comparator

entity bit2com is                
    Port ( a,b: in  STD_LOGIC_vector(1 downto 0);
           y : out  STD_LOGIC);
end bit2com;

architecture Behavioral of bit2com is

signal p0,p1,p2:std_logic;

begin

p0  <= a(1) and not b(1);
p1  <= a(0) and a(1) and not b(0);
p2<=a(0) and not b(0) and not b(1);
y <= p0 or p1 or p2;

end Behavioral;

equality Comparator

entity comaeqb is

    Port ( a,b: in  STD_LOGIC_vector(1 downto 0);
           y : out  STD_LOGIC);
end comaeqb;

architecture Behavioral of comaeqb is

signal p0,p1,p2,p3:std_logic;
begin

p0  <= a(0) and a(1) and b(0) and b(1);
p1  <= a(0) and not a(1) and b(0) and not b(1);

p2<=not a(0) and not a(1) and not b(0) and not b(1);
p3<=not a(0) and a(1) and not b(0) and b(1);
y <= p0 or p1 or p2 or p3;

How can I use this to make a 4 bit greater than Comparator?


Solution

  • As I see, you tried to create 4-bit comparator from 2-bit comparators (> and =). But I think there are 2 answers for you question:

    1. If you just want to create 4-bit comparator without any comparator (independent), please declare A and B as signed or unsigned to compare (you can convert to this type if you use std_logic_vector). There are two libraries to use: arith and numeric_std (just use one of them, both is violated).
    2. If you have to use 2 bit comparators. Use this way:

    Propose A = [A3 A2 A1 A0] and B = [B3 B2 B1 B0]. Run two steps:

    Step 1 compare two MSB with yours comparators:

    if [A3 A2] > [B3 B2] then
      A_greater_than_B <= '1';
    elsif [A3 A2] < [B3 B2] then
      A_greater_than_B <= '0';
    else -- [A3 A2] = [B3 B2]
    -- next step >>>
    end if;
    

    Step 2 compare two LSBs with yours comparators with similar method with Step 1. This branch is occurred when [A3 A2] =[ B3 B2]. Result of step 2 is result of 4-bit comparator. For example, if [A1 A0] = [B1 B0] then A = B.