Skip to content
BetterDL

Comparison by subtraction

Also called: compare by subtracting, subtract-and-compare, compare instruction

Comparing two numbers by computing A − B and reading the flags: Z for equal, the carry flag for unsigned order, and N ⊕ V for signed order.

A processor doesn't need a separate comparator to compare numbers. It subtracts, throws the difference away, and reads the status flags. A compare instruction does exactly this.

After computing A − B as A + + 1:

  • Equal: Z = 1, because the difference is zero.
  • Unsigned A < B: C = 0, because a borrow happened. Unsigned A ≥ B: C = 1.
  • Signed A < B: = 1. Signed A ≥ B: = 0.

Why N ⊕ V and not just N? If the subtraction didn't overflow, the sign of the difference is right, so N alone answers "is A − B negative?". If it did overflow (V = 1), the sign is flipped, so N is wrong and must be inverted. XOR with V does exactly that.

Greater-than and less-or-equal add Z: unsigned A > B is C = 1 and Z = 0; signed A ≤ B is N ⊕ V = 1 or Z = 1.

One subtraction answers the signed and the unsigned question at the same time. The program picks the flags that match its data type.

000
011
101
110

Worked examples

Example

Signed: when N gives the wrong answer

A = 0110 (+6), B = 1101 (−3). Compute A − B = 0110 + 0010 + 1.

  1. 1.

    Bit 0: 0 + 0 + 1 → 1, carry 0. Bit 1: 1 + 1 → 0, carry 1.

  2. 2.

    Bit 2: 1 + 0 + 1 → 0, carry 1, so C3 = 1. Bit 3: 0 + 0 + 1 → 1, carry 0, so C4 = 0.

  3. 3.

    Result 1001: N = 1, so the difference looks negative.

  4. 4.

    V = C4 ⊕ C3 = 1: 6 − (−3) = 9 didn't fit, so the sign is flipped.

  5. 5.

    N ⊕ V = 0, so A is not less than B. Correct: 6 > −3.

Example

Unsigned: the same bits, the other question

Read the same patterns as unsigned: A = 6, B = 13. The subtraction above had no carry-out, so C = 0: a borrow, meaning A < B. Correct, since 6 < 13. One subtraction, two different but correct verdicts.

Common mistakes

  • Using N alone for a signed comparison.

  • Using C for signed numbers, or N ⊕ V for unsigned ones.

  • Reading C = 1 as A < B. After A − B, C = 1 means A ≥ B.

Practice Comparison by subtraction

Interactive questions with instant feedback and a worked solution for every wrong answer.

Learn it step by step

Comparison by subtraction is taught in Adders and ALUs.