import json
import sys
class SRLatch:
def __init__(self, q: int = 0) -> None:
self.q = q
def step(self, s: int, r: int) -> tuple[int, str]:
if s == 0 and r == 0:
return self.q, "HOLD"
if s == 1 and r == 0:
self.q = 1
return self.q, "SET"
if s == 0 and r == 1:
self.q = 0
return self.q, "RESET"
return self.q, "FORBIDDEN"
class DFlipFlop:
def __init__(self, initial: int = 0) -> None:
self.q = initial
self.prev_clk = 0
def update(self, d: int, clk: int) -> int:
if self.prev_clk == 0 and clk == 1:
self.q = d
self.prev_clk = clk
return self.q
class Register4Bit:
def __init__(self) -> None:
self.bits = [DFlipFlop() for _ in range(4)]
def tick(self, value: int, write_en: int = 1) -> int:
# Simulate falling-to-rising clock edge
for ff in self.bits:
ff.update(ff.q, 0)
for i, ff in enumerate(self.bits):
d_in = ((value >> i) & 1) if write_en else ff.q
ff.update(d_in, 1)
return self.read()
def read(self) -> int:
out = 0
for i, ff in enumerate(self.bits):
out |= ff.q << i
return out
def run_cases() -> list[dict]:
cases: list[dict] = []
# Case 1: SR Latch transitions (SET -> HOLD -> RESET -> HOLD -> FORBIDDEN)
sr = SRLatch(0)
sr_trace = [
sr.step(1, 0),
sr.step(0, 0),
sr.step(0, 1),
sr.step(0, 0),
sr.step(1, 1),
]
actual1 = {"sr_trace": sr_trace}
expected1 = {
"sr_trace": [
(1, "SET"),
(1, "HOLD"),
(0, "RESET"),
(0, "HOLD"),
(0, "FORBIDDEN"),
]
}
cases.append(
{
"name": "sr_latch_state_machine",
"summary": "验证 SR 锁存器置位、保持、复位及非法输入状态的记忆行为",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
}
)
# Case 2: Rising-edge D Flip-Flop ignores D changes except on 0->1 clock edge
dff = DFlipFlop(0)
events = [
(1, 0), # D=1, CLK=0 -> no latch, Q=0
(1, 1), # D=1, CLK=0->1 -> latch 1, Q=1
(0, 1), # D=0, CLK stays 1 -> hold 1
(0, 0), # CLK falls -> hold 1
(0, 1), # D=0, CLK=0->1 -> latch 0, Q=0
]
q_trace = [dff.update(d, clk) for d, clk in events]
actual2 = {"q_trace": q_trace}
expected2 = {"q_trace": [0, 1, 1, 1, 0]}
cases.append(
{
"name": "edge_triggered_d_flip_flop",
"summary": "验证上升沿触发 D 触发器仅在时钟 0→1 跳变瞬间采样并锁存输入 D",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
}
)
# Case 3: 4-bit register multi-cycle write and write-enable hold
reg = Register4Bit()
ops = [
(0b0101, 1), # write 5
(0b1111, 0), # hold 5 (write_en=0)
(0b1010, 1), # write 10
(0b0011, 0), # hold 10
(0b1100, 1), # write 12
]
reg_trace = [reg.tick(val, we) for val, we in ops]
actual3 = {"register_values": reg_trace, "final_binary": format(reg.read(), "04b")}
expected3 = {"register_values": [5, 5, 10, 10, 12], "final_binary": "1100"}
cases.append(
{
"name": "four_bit_register_cycles",
"summary": "验证 4 位并行寄存器在写使能控制下按时钟周期加载与保持数据",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
}
)
# Case 4: Synchronous accumulator (Register + Combinational Adder + Clock)
acc = Register4Bit()
steps = [3, 4, 2, 5] # 0->3->7->9->14
acc_history = []
for addend in steps:
nxt = (acc.read() + addend) & 0xF
acc_history.append(acc.tick(nxt, 1))
actual4 = {
"accumulator_history": acc_history,
"has_state_memory": acc_history[-1] != steps[-1],
}
expected4 = {"accumulator_history": [3, 7, 9, 14], "has_state_memory": True}
cases.append(
{
"name": "synchronous_accumulator_datapath",
"summary": "验证寄存器与组合加法器组成同步时序累加器,体现输出依赖历史状态",
"expected": expected4,
"actual": actual4,
"passed": actual4 == expected4,
}
)
return cases
def main() -> None:
payload = {
"version": f"CPython {sys.version.split()[0]}",
"cases": run_cases(),
}
print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线计算机组成原理数值计算、逻辑门电路与体系结构仿真验证器(未在真实浏览器中执行来源交互脚本,也未连接外部网络)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线计算机组成原理数值计算、逻辑门电路与体系结构仿真验证器(未在真实浏览器中执行来源交互脚本,也未连接外部网络)。
入口文件:projects/computer-organization-flip-flops-and-registers-lab/explore-flip-flops-and-registers.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-flip-flops-and-registers.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线计算机组成原理数值计算、逻辑门电路与体系结构仿真验证器(未在真实浏览器中执行来源交互脚本,也未连接外部网络)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2625.zip
课程关联工程包(登记关联22章) · 含当前章节或实例 · mbskycom202612a2616.zip