116. AND 指令原语
实现与寻址方式无关的 AND 行为。
第 116 / 356 · tests/chapter_01_cpu/test_116_instruction_and_a.py
在这一步中,只在 `emulator/cpu/instructions.py 中添加 and_a`。操作码导入和 AND 的各种寻址模式在第 117-124 课中陆续加入。
为什么需要这一步
把 AND 定义为面向数值的原语,可以把累加器和标志位语义集中在一处,让每个寻址模式的处理函数都能一致地复用它们。
建议实现
def and_a(cpu: CPU, value: int):
result_8 = (cpu.a & value) & 0xFF
# Flags:
cpu.flags.set_zero_flag(result_8 == 0)
cpu.flags.set_negative_flag((result_8 & 0b1000_0000) != 0)
cpu.a = result_8这种面向数值的函数签名把指令语义与地址解码分离开来。结果被限制在 8 位以内,存入 A,Zero 反映结果是否为零,Negative 反映结果的第 7 位。Carry、Overflow、内存、X、Y 和 PC 保持不变,因为这个函数从不触碰它们。
误解澄清:`value 不是需要通过 cpu.bus 读取的地址;这样的读取由操作码处理函数完成。本课不涉及的内容:把 and_a 导入 emulator/cpu/opcodes.py` 以及每一个 AND 操作码(第 117-124 课),还有第 125-145 课中的 ORA、EOR 和 BIT 相关符号。
运行本课
uv run pytest tests/chapter_01_cpu/test_116_instruction_and_a.py -v