"""Offline Computer Organization lab for Chapter 06 (character-encoding)."""
import json
VERSION = "CPython 3.12.14 offline computer organization simulation verifier"
def case_ascii_layout_and_case_bit():
actual = {
"ascii_total": 1 << 7,
"digit_range": (ord("0"), ord("9")),
"upper_range": (ord("A"), ord("Z")),
"lower_range": (ord("a"), ord("z")),
"lf_cr": (ord("\n"), ord("\r")),
"case_diff": ord("a") - ord("A"),
"A_bin": format(ord("A"), "08b"),
"a_bin": format(ord("a"), "08b"),
"bit5_toggle_to_lower": chr(ord("A") | 0x20),
"bit5_clear_to_upper": chr(ord("z") & ~0x20),
}
expected = {
"ascii_total": 128,
"digit_range": (48, 57),
"upper_range": (65, 90),
"lower_range": (97, 122),
"lf_cr": (10, 13),
"case_diff": 32,
"A_bin": "01000001",
"a_bin": "01100001",
"bit5_toggle_to_lower": "a",
"bit5_clear_to_upper": "Z",
}
return {
"name": "ascii_layout_and_case_bit",
"summary": "校验 7 位 ASCII 关键码段(数字/大小写/LF/CR)及第 5 位(0x20=32)位运算切换大小写机制",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_unicode_and_utf8_variable_length():
samples = [
("A", 0x0041, 1, "0"),
("é", 0x00E9, 2, "110"),
("你", 0x4F60, 3, "1110"),
("好", 0x597D, 3, "1110"),
("😀", 0x1F600, 4, "11110"),
("\U000E0001", 0xE0001, 4, "11110"),
]
rows = []
for ch, cp, exp_len, prefix in samples:
raw = ch.encode("utf-8")
first_bin = format(raw[0], "08b")
cont_ok = all(format(b, "08b").startswith("10") for b in raw[1:])
rows.append(
{
"cp_hex": f"U+{ord(ch):04X}",
"cp_match": ord(ch) == cp,
"byte_len": len(raw),
"prefix_ok": first_bin.startswith(prefix),
"cont_ok": cont_ok,
}
)
# Mixed string space comparison
mixed = "Hello 你好"
actual = {
"rows": rows,
"ni_utf8_hex": "你".encode("utf-8").hex(" ").upper(),
"mixed_utf8_bytes": len(mixed.encode("utf-8")),
"mixed_utf16le_bytes": len(mixed.encode("utf-16-le")),
"mixed_utf32le_bytes": len(mixed.encode("utf-32-le")),
}
expected = {
"rows": [
{"cp_hex": "U+0041", "cp_match": True, "byte_len": 1, "prefix_ok": True, "cont_ok": True},
{"cp_hex": "U+00E9", "cp_match": True, "byte_len": 2, "prefix_ok": True, "cont_ok": True},
{"cp_hex": "U+4F60", "cp_match": True, "byte_len": 3, "prefix_ok": True, "cont_ok": True},
{"cp_hex": "U+597D", "cp_match": True, "byte_len": 3, "prefix_ok": True, "cont_ok": True},
{"cp_hex": "U+1F600", "cp_match": True, "byte_len": 4, "prefix_ok": True, "cont_ok": True},
{"cp_hex": "U+E0001", "cp_match": True, "byte_len": 4, "prefix_ok": True, "cont_ok": True},
],
"ni_utf8_hex": "E4 BD A0",
"mixed_utf8_bytes": 12,
"mixed_utf16le_bytes": 16,
"mixed_utf32le_bytes": 32,
}
return {
"name": "unicode_and_utf8_variable_length",
"summary": "验证 Unicode 码点与 UTF-8 1/2/3/4 字节前导位及续字节规则,并对比 UTF-8/UTF-16/UTF-32 字节占用",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_mojibake_and_gbk_comparison():
text = "你好"
utf8_bytes = text.encode("utf-8")
gbk_bytes = text.encode("gbk")
# Decoding UTF-8 bytes of "你好" (6 bytes) as GBK produces mojibake (3 GBK chars)
wrong_gbk = utf8_bytes.decode("gbk")
wrong_latin1 = utf8_bytes.decode("latin-1")
def safe_decode(data: bytes, encodings=("utf-8", "gbk", "latin-1")):
for enc in encodings:
try:
return data.decode(enc), enc
except UnicodeDecodeError:
continue
return data.decode("latin-1", errors="replace"), "latin-1"
rec_utf8 = safe_decode("你好世界".encode("utf-8"))
rec_gbk = safe_decode("计算机".encode("gbk"))
actual = {
"utf8_len": len(utf8_bytes),
"gbk_len": len(gbk_bytes),
"utf8_hex": utf8_bytes.hex(" ").upper(),
"gbk_hex": gbk_bytes.hex(" ").upper(),
"wrong_gbk_is_mojibake": wrong_gbk != text and len(wrong_gbk) == 3,
"wrong_latin1_len": len(wrong_latin1),
"safe_decode_utf8": list(rec_utf8),
"safe_decode_gbk": list(rec_gbk),
}
expected = {
"utf8_len": 6,
"gbk_len": 4,
"utf8_hex": "E4 BD A0 E5 A5 BD",
"gbk_hex": "C4 E3 BA C3",
"wrong_gbk_is_mojibake": True,
"wrong_latin1_len": 6,
"safe_decode_utf8": ["你好世界", "utf-8"],
"safe_decode_gbk": ["计算机", "gbk"],
}
return {
"name": "mojibake_and_gbk_comparison",
"summary": "对比中文在 UTF-8(3 字节) 与 GBK(2 字节) 下的字节长度,重现解码错配乱码并验证编码探测解码",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_utf8_bom_impact():
bom = b"\xef\xbb\xbf"
shebang_with_bom = bom + b"#!/bin/bash\n"
json_with_bom = (bom + b'{"ok": true}').decode("utf-8")
try:
json.loads(json_with_bom)
json_rejected_bom = False
except json.JSONDecodeError:
json_rejected_bom = True
cleaned = json_with_bom.lstrip("\ufeff")
actual = {
"bom_hex": bom.hex(" ").upper(),
"shebang_starts_with_hash_bang": shebang_with_bom.startswith(b"#!"),
"json_rejected_bom": json_rejected_bom,
"cleaned_json_ok": json.loads(cleaned)["ok"],
"html_meta_charset": '<meta charset="UTF-8">',
"http_header": "Content-Type: text/html; charset=utf-8",
}
expected = {
"bom_hex": "EF BB BF",
"shebang_starts_with_hash_bang": False,
"json_rejected_bom": True,
"cleaned_json_ok": True,
"html_meta_charset": '<meta charset="UTF-8">',
"http_header": "Content-Type: text/html; charset=utf-8",
}
return {
"name": "utf8_bom_impact",
"summary": "实测 UTF-8 BOM(EF BB BF)对 #!/bin/bash 与 JSON 解析器的破坏效应及无 BOM 规范声明",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_ascii_layout_and_case_bit(),
case_unicode_and_utf8_variable_length(),
case_mojibake_and_gbk_comparison(),
case_utf8_bom_impact(),
]
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-character-encoding-lab/explore-character-encoding.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-character-encoding.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线计算机组成原理数值计算、逻辑门电路与体系结构仿真验证器(未在真实浏览器中执行来源交互脚本,也未连接外部网络)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联22章) · 含当前章节或实例 · mbskycom202612a2616.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2620.zip