010. LDA 标志位

在立即寻址 LDA 之后更新 Zero 和 Negative 标志位。

10 / 356 · tests/chapter_01_cpu/test_010_LDA_flags.py

需要更新的文件

emulator/cpu/cpu.py

位置

CPU.step, inside the existing $A9 immediate-LDA branch

此步骤存在的原因

6502 会记录 LDA 结果是否为零,以及第 7 位是否被置位。后续的分支指令会用到这些状态位,因此置位和清零都必须正确工作。

完整示例实现

class CPU:
    # Keep the existing methods from Tests 004, 008, and 009.

    def step(self) -> None:
        opcode = self.fetch_byte()

        if opcode == 0xA9:
            self.a = self.fetch_byte()

            if self.a == 0:
                self.p |= 1 << 1
            else:
                self.p &= ~(1 << 1)

            if self.a & (1 << 7):
                self.p |= 1 << 7
            else:
                self.p &= ~(1 << 7)

            return

        raise NotImplementedError(
            f"Opcode {opcode:02X} not implemented"
        )

结果表

A=$00 -> Z=1, N=0
A=$7F -> Z=0, N=0
A=$80 -> Z=0, N=1

重要不变量

只有 Zero 和 Negative 位会被改变;复位时的 Interrupt Disable 位以及其他所有状态位都保持先前的值。

常见误解

这里的“Negative”并不是在执行有符号运算。它只是表示 8 位结果的第 7 位被置位了。

范围之外

  • 测试 012 中引入的具名标志常量和共享辅助函数
  • 绝对寻址和零页寻址的 LDA
  • 指令周期计数

运行本课

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