"""Offline Computer Organization lab for Chapter 03 (number-system-conversion)."""
import json
VERSION = "CPython 3.12.14 offline computer organization simulation verifier"
HEX_MAP = {f"{i:04b}": f"{i:X}" for i in range(16)}
REV_HEX_MAP = {v: k for k, v in HEX_MAP.items()}
def dec_to_bin_steps(n: int) -> tuple[str, list[tuple[int, int, int]]]:
if n == 0:
return "0", [(0, 0, 0)]
steps = []
cur = n
while cur > 0:
q, r = divmod(cur, 2)
steps.append((cur, q, r))
cur = q
bits = "".join(str(r) for _, _, r in reversed(steps))
return bits, steps
def bin_to_dec(b: str) -> int:
total = 0
for i, ch in enumerate(b):
total += int(ch) * (2 ** (len(b) - 1 - i))
return total
def bin_to_hex(b: str) -> str:
pad = (-len(b)) % 4
padded = ("0" * pad) + b
return "".join(HEX_MAP[padded[i : i + 4]] for i in range(0, len(padded), 4))
def hex_to_bin(h: str) -> str:
raw = "".join(REV_HEX_MAP[ch] for ch in h.upper())
return raw.lstrip("0") or "0"
def case_decimal_to_binary_division():
b42, steps42 = dec_to_bin_steps(42)
b82, _ = dec_to_bin_steps(82)
b255, _ = dec_to_bin_steps(255)
b0, _ = dec_to_bin_steps(0)
actual = {
"42_bin": b42,
"42_steps": steps42,
"82_bin": b82,
"255_bin": b255,
"0_bin": b0,
}
expected = {
"42_bin": "101010",
"42_steps": [(42, 21, 0), (21, 10, 1), (10, 5, 0), (5, 2, 1), (2, 1, 0), (1, 0, 1)],
"82_bin": "1010010",
"255_bin": "11111111",
"0_bin": "0",
}
return {
"name": "decimal_to_binary_division",
"summary": "用除 2 取余法验证十进制 42、82、255、0 的二进制转换与每步商余序列",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_weighted_expansion_three_bases():
dec_42 = 4 * (10 ** 1) + 2 * (10 ** 0)
bin_42 = bin_to_dec("101010")
hex_42 = 2 * (16 ** 1) + 10 * (16 ** 0)
bit_positions = [5, 4, 3, 2, 1, 0]
weights = [2 ** p for p in bit_positions]
bits = [1, 0, 1, 0, 1, 0]
products = [b * w for b, w in zip(bits, weights)]
actual = {
"dec_42": dec_42,
"bin_42": bin_42,
"hex_42": hex_42,
"weights": weights,
"products": products,
"sum_products": sum(products),
}
expected = {
"dec_42": 42,
"bin_42": 42,
"hex_42": 42,
"weights": [32, 16, 8, 4, 2, 1],
"products": [32, 0, 8, 0, 2, 0],
"sum_products": 42,
}
return {
"name": "weighted_expansion_three_bases",
"summary": "验证十进制 42、二进制 101010 与十六进制 2A 的按权展开一致性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_nibble_hex_lookup_table():
all_ok = all(
HEX_MAP[f"{i:04b}"] == f"{i:X}" and REV_HEX_MAP[f"{i:X}"] == f"{i:04b}"
for i in range(16)
)
actual = {
"table_entries": len(HEX_MAP),
"all_16_bijection_ok": all_ok,
"bin_11111111_to_hex": "0x" + bin_to_hex("11111111"),
"bin_101010_to_hex": "0x" + bin_to_hex("101010"),
"bin_1010010_to_hex": "0x" + bin_to_hex("1010010"),
"hex_52_to_bin": hex_to_bin("52"),
"hex_FF_to_bin": hex_to_bin("FF"),
"literal_check": (0xFF == 0b11111111 == 255),
}
expected = {
"table_entries": 16,
"all_16_bijection_ok": True,
"bin_11111111_to_hex": "0xFF",
"bin_101010_to_hex": "0x2A",
"bin_1010010_to_hex": "0x52",
"hex_52_to_bin": "1010010",
"hex_FF_to_bin": "11111111",
"literal_check": True,
}
return {
"name": "nibble_hex_lookup_table",
"summary": "验证全部 16 组 4 位二进制与十六进制双向查表映射及 0x/0b 字面量等价性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_binary_bridge_and_compactness():
# Use binary as bridge: hex -> bin -> dec and dec -> bin -> oct/hex
samples = [0x2A, 0x52, 0xFF, 0x1A3F]
bridge_ok = True
for val in samples:
b = dec_to_bin_steps(val)[0]
h = bin_to_hex(b)
b_back = hex_to_bin(h)
d_back = bin_to_dec(b_back)
if d_back != val:
bridge_ok = False
word = "MBSKY"
dec_seq = [ord(c) for c in word]
bin_len = sum(len(f"{x:08b}") for x in dec_seq)
hex_len = sum(len(f"{x:02X}") for x in dec_seq)
actual = {
"bridge_roundtrip_ok": bridge_ok,
"oct_of_42": oct(42),
"bin_to_hex_length_ratio": bin_len // hex_len,
"hex_of_1A3F_dec": bin_to_dec(hex_to_bin("1A3F")),
}
expected = {
"bridge_roundtrip_ok": True,
"oct_of_42": "0o52",
"bin_to_hex_length_ratio": 4,
"hex_of_1A3F_dec": 6719,
}
return {
"name": "binary_bridge_and_compactness",
"summary": "验证以二进制为中间桥梁实现十/八/十六进制往返转换及二进制与十六进制 4:1 长度压缩比",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_decimal_to_binary_division(),
case_weighted_expansion_three_bases(),
case_nibble_hex_lookup_table(),
case_binary_bridge_and_compactness(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线计算机组成原理数值计算、逻辑门电路与体系结构仿真验证器(未在真实浏览器中执行来源交互脚本,也未连接外部网络)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线计算机组成原理数值计算、逻辑门电路与体系结构仿真验证器(未在真实浏览器中执行来源交互脚本,也未连接外部网络)。
入口文件:projects/computer-organization-number-system-conversion-lab/explore-number-system-conversion.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-number-system-conversion.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线计算机组成原理数值计算、逻辑门电路与体系结构仿真验证器(未在真实浏览器中执行来源交互脚本,也未连接外部网络)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2635.zip
课程关联工程包(登记关联22章) · 含当前章节或实例 · mbskycom202612a2616.zip