Topic 19 · Digital Electronics

Comparators
1-bit · 4-bit · Magnitude

Equality and magnitude comparison from the gate level up — including cascading, signed comparison, and common VLSI applications.

XNOR EqualityMagnitude74HC85 CascadingSignedZero DetectorVerilog

1-bit Comparator

ABA=B (XNOR)A>BA<B
00100
01001
10010
11100
EQ = A XNOR B  |  A>B = A · B̄  |  A<B = Ā · B

Interactive N-bit Comparator

Input A (0–255)
Input B (0–255)
Binary: A =   B =
A = B
A > B
A < B
Zero (A)

4-bit Magnitude Comparator — 74HC85

Compares A[3:0] vs B[3:0] starting from MSB. Cascade inputs (I_A>B, I_A=B, I_A<B) allow chaining: connect outputs of lower chip to cascade inputs of upper chip.

ConditionOutput O_A>BOutput O_A=BOutput O_A<B
A > B100
A = B (and I_A=B=1)010
A < B001

For a single 4-bit comparator: set I_A>B=0, I_A=B=1, I_A<B=0

Verilog Comparators

// Unsigned N-bit comparator
module cmp_unsigned #(parameter N=8) (
  input  logic [N-1:0] a, b,
  output logic         eq, gt, lt
);
  assign eq = (a == b);
  assign gt = (a  > b);
  assign lt = (a  < b);
endmodule

// Signed comparison — use $signed() or signed declaration
module cmp_signed #(parameter N=8) (
  input  logic signed [N-1:0] a, b,
  output logic                  eq, gt, lt
);
  assign eq = (a == b);
  assign gt = (a  > b);  // signed comparison
  assign lt = (a  < b);
endmodule

// Zero detector (reduction NOR)
assign zero = ~|a;   // 1 if all bits of a are 0

// 74HC85-style cascadable 4-bit comparator
module cmp4_cascade (
  input  logic [3:0] a, b,
  input  logic       i_gt, i_eq, i_lt,  // cascade in
  output logic       o_gt, o_eq, o_lt   // cascade out
);
  always_comb begin
    if      (a > b) begin o_gt=1; o_eq=0; o_lt=0; end
    else if (a < b) begin o_gt=0; o_eq=0; o_lt=1; end
    else            begin o_gt=i_gt; o_eq=i_eq; o_lt=i_lt; end
  end
endmodule

Comparator Applications

ApplicationComparison used
ALU zero flag~|result (reduction NOR)
Address range checkaddr >= BASE && addr < LIMIT
Priority arbiterLargest active priority wins
Loop counter terminationcount == MAX
Cache tag comparetag == stored_tag → hit
ADC threshold detectdata > threshold → trigger
Sorting networkCompare-and-swap elements

Frequently Asked Questions

How does a 1-bit comparator work?

EQ = XNOR(A,B). A>B = A AND NOT B. A<B = NOT A AND B. These are the building blocks for wider comparators.

What is the difference between signed and unsigned comparison in Verilog?

Unsigned: 8'hFF = 255 > 0. Signed: 8'hFF = -1 < 0. Declare logic signed [7:0] or use $signed() cast for correct signed comparison.

What is a zero detector?

Outputs 1 when all input bits are 0. In Verilog: assign zero = ~|a; (reduction NOR). Used for ALU zero flag, loop termination, and equality-to-zero checks.