076. Dec 零页
添加 DEC 并接入零页寻址(`0xC6`)。
第 76 / 356 · tests/chapter_01_cpu/test_076_DEC_zero_page.py
在本步骤中,添加 emulator/cpu/instructions.py:dec,以及 emulator/cpu/opcodes.py 中零页寻址的导入、处理函数和表接线。与 INC 不同,DEC 没有单独的原语步骤。
本步骤存在的原因
先建立一个内存递减原语,再暴露它的第一种寻址模式。之后的 DEC 处理函数只需解析出有效地址即可。
在 emulator/cpu/instructions.py 中的建议实现,位于 inc 之后:
def dec(cpu: CPU, address: int):
value = cpu.bus.read(address)
result = value - 1
result_8 = result & 0xFF
# Set flags
cpu.flags.set_negative_flag((result_8 & 0b1000_0000) != 0)
cpu.flags.set_zero_flag(result_8 == 0)
# Set value on address
cpu.bus.write(address, result_8)在 emulator/cpu/opcodes.py 中完成第 076 课的接线:
from emulator.cpu.instructions import lda, sta, ldx, stx, ldy, sty, tax, txa, tay, tya, adc, sbc, inc, dec
def dec_zero_page(cpu: CPU):
addr = zero_page(cpu)
dec(cpu, addr)在现有的 OPCODE_TABLE 中添加这条完全一致的条目:
0xC6: dec_zero_page,不变量:DEC 接收一个地址,并通过总线访问内存;掩码运算使得 $00 - 1 == $FF;Zero 和 Negative 反映存储的字节;Carry、Overflow 以及 A/X/Y 保持不变;零页寻址消耗一个操作数字节,整条指令共两个字节。
常见误解:DEC 不是 SBC。它既不消耗也不更新 Carry,也不对 A 进行操作;零页操作数指定的是内存位置。
范围之外:零页-X、绝对寻址和绝对-X 的 DEC 接线属于第 077-079 课。
运行本课
uv run pytest tests/chapter_01_cpu/test_076_DEC_zero_page.py -v