017. Lda 零页,X 寻址

添加零页,X 寻址的 LDA($B5)。

17 / 356 · tests/chapter_01_cpu/test_017_LDA_zero_page_x.py

要更新的文件

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

位置

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

为什么需要这一步

零页,X 寻址将寄存器 X 与一个 8 位基地址相加。相加结果在页 $00 内回绕,而不是进位到页 $01。

完整示例实现

# 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,
}

重要不变量

final_address = (operand + X) & 0xFF

常见误解

$FF + X=$01 得到 $0000,而不是 $0100。这条回绕规则是零页变址寻址特有的。

范围之外

  • 绝对,X 寻址的跨页
  • 零页,Y
  • 周期时序

运行本课

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