017. Lda zero page x

Add zero-page,X LDA ($B5).

Lesson 17 of 356 · tests/chapter_01_cpu/test_017_LDA_zero_page_x.py

Files to update

emulator/cpu/addressing_modes.py
emulator/cpu/opcodes.py

Locations

addressing_modes.zero_page_x
opcodes.lda_zero_page_x
opcodes.OPCODE_TABLE[$B5]

Why this step exists

Zero-page,X adds register X to an 8-bit base address. The addition wraps within page $00 rather than carrying into page $01.

Complete example implementation

# emulator/cpu/addressing_modes.py
def zero_page_x(cpu) -> int:
    base = cpu.fetch_byte()
    return (base + cpu.x) & 0xFF


# emulator/cpu/opcodes.py
from emulator.cpu.addressing_modes import zero_page_x


def lda_zero_page_x(cpu) -> None:
    address = zero_page_x(cpu)
    lda(cpu, cpu.bus.read(address))


OPCODE_TABLE = {
    # Preserve existing entries.
    0xB5: lda_zero_page_x,
}

Important invariant

final_address = (operand + X) & 0xFF

Common misconception

$FF + X=$01 produces $0000, not $0100. This wrapping rule is specific to zero-page indexed addressing.

Out of scope

  • absolute,X page crossing
  • zero-page,Y
  • cycle timing

Run this lesson

uv run pytest tests/chapter_01_cpu/test_017_LDA_zero_page_x.py -v