155. Instruction cpx
implement addressing-independent CPX behavior.
Lesson 155 of 356 · tests/chapter_01_cpu/test_155_instruction_cpx.py
Why this step exists
CPX needs one value-oriented definition of its no-borrow, equality, and wrapped-subtraction flags before its addressing-specific opcodes are added.
In this step, after all CMP lessons, add exactly this symbol to `emulator/cpu/instructions.py`:
def cpx(cpu: CPU, value: int):
result_8 = (cpu.x - value) & 0xFF
# Flags:
cpu.flags.set_carry_flag(cpu.x >= value)
cpu.flags.set_zero_flag(cpu.x == value)
cpu.flags.set_negative_flag((result_8 & 0b1000_0000) !=0)The wrapped subtraction exists only to derive Negative. Carry means no unsigned borrow (X >= value), and Zero tests equality. X, the operand, memory, A, Y, PC, and Overflow are invariant because no result is stored and those locations are untouched.
Misconception: CPX is not SBC and neither consumes Carry nor writes the subtraction back to X. Out of scope: importing `cpx into emulator/cpu/opcodes.py` and its immediate, zero-page, and absolute handlers (lessons 156-158), plus CPY (159-162).
Run this lesson
uv run pytest tests/chapter_01_cpu/test_155_instruction_cpx.py -v