Signed Comparison

6502 Signed Comparison

Understanding the N and V Flags in CMP Operations

The Key Insight

When performing a CMP instruction (which computes A - M), the 6502 sets the Negative (N) and Overflow (V) flags. For signed comparisons, when N = V, it means A ≥ M (signed). But why?

The answer lies in understanding how two's complement arithmetic works and what the overflow flag actually tells us about the sign bit.

6502 Signed Comparison: CMP (A - M) Why N = V means A ≥ M (signed) Key Insight: V (overflow) = 1 means the sign bit flipped incorrectly So when N = V, they "cancel out" and give the true relationship Case 1: Both Positive A = +70 ($46), M = +30 ($1E) A - M = +40 ($28) N = 0 V = 0 N = V Result positive, no overflow ✓ A ≥ M Case 2: Pos - Neg A = +100 ($64), M = -30 ($E2) 130 → -126 ($82) overflow! N = 1 V = 1 N = V Looks negative, but overflowed ✓ A ≥ M Case 3: Neg - Pos A = -30 ($E2), M = +100 ($64) -130 → +126 ($7E) overflow! N = 0 V = 1 N ≠ V Looks positive, but overflowed ✗ A < M Case 4: Both Positive A = +30 ($1E), M = +70 ($46) A - M = -40 ($D8) N = 1 V = 0 N ≠ V Result negative, no overflow ✗ A < M Case 5: Both Negative A = -30 ($E2), M = -70 ($BA) A - M = +40 ($28) N = 0 V = 0 N = V Result positive, no overflow ✓ A ≥ M Case 6: Both Negative A = -70 ($BA), M = -30 ($E2) A - M = -40 ($D8) N = 1 V = 0 N ≠ V Result negative, no overflow ✗ A < M The Pattern: When overflow (V=1), the sign bit (N) is inverted from what it "should" be So when N = V, they're either BOTH showing the truth or BOTH inverted → This means the actual signed result is non-negative: A ≥ M 6502 Branch Instructions: BPL (Branch if Plus) — Branch if N=0 BMI (Branch if Minus) — Branch if N=1 BVC (Branch if Overflow Clear) — Branch if V=0 BVS (Branch if Overflow Set) — Branch if V=1 For signed CMP: Use: BPL after CMP for A ≥ M Or: Check if N = V with EOR trick (there's no single branch for N=V)

Why This Works: Two's Complement Arithmetic

  • CMP performs subtraction: When you execute CMP #$E2, the 6502 computes A - M internally as A + (~M + 1) using two's complement negation.
  • Overflow means the sign bit "lied": The V flag is set when adding two numbers with the same sign produces a result with the opposite sign - this is overflow.
  • N = V catches the truth: When both flags match, either they're both correctly showing a positive result (N=0, V=0) or they're both showing that an overflow inverted what should be positive (N=1, V=1).
  • No single branch instruction: The 6502 doesn't have a "branch if N = V" instruction, so you need to use a sequence like checking with BIT or using EOR to compare the flags.

6502 Microprocessor Reference | Two's Complement Arithmetic Visualization