蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 8 位三码转换、模 256 减法统一性、4 位补码环与 -128 溢出边界

PYTHONWindows x64、CPython 3.12.14 离线计算机组成原理数值计算、逻辑门电路与体系结构仿真验证器(未在真实浏览器中执行来源交互脚本,也未连接外部网络)。explore-negative-numbers-complement.py
explore-negative-numbers-complement.py190 行
"""Offline Computer Organization lab for Chapter 04 (negative-numbers-complement)."""
import json

VERSION = "CPython 3.12.14 offline computer organization simulation verifier"


def to_twos_complement(n: int, bits: int = 8) -> str:
    minimum = -(1 << (bits - 1))
    maximum = (1 << (bits - 1)) - 1
    if not (minimum <= n <= maximum):
        raise ValueError("out of range")
    return format(n & ((1 << bits) - 1), f"0{bits}b")


def from_twos_complement(binary: str) -> int:
    unsigned = int(binary, 2)
    bits = len(binary)
    return unsigned - (1 << bits) if binary[0] == "1" else unsigned


def encode_8bit_all(n: int) -> dict:
    twos = to_twos_complement(n, 8)
    if n >= 0:
        orig = format(n, "08b")
        ones = orig
    elif n > -128:
        mag = format(-n, "07b")
        orig = "1" + mag
        ones = "1" + "".join("1" if c == "0" else "0" for c in mag)
    else:
        orig = None
        ones = None
    return {"sign_magnitude": orig, "ones": ones, "twos": twos}


def case_three_encodings_comparison():
    values = [5, -5, 0, 20, -20, 127, -127, -128]
    table = {str(v): encode_8bit_all(v) for v in values}
    roundtrip = {str(v): from_twos_complement(to_twos_complement(v, 8)) for v in [5, -5, -20, 0, 127, -128]}
    actual = {"table": table, "roundtrip": roundtrip}
    expected = {
        "table": {
            "5": {"sign_magnitude": "00000101", "ones": "00000101", "twos": "00000101"},
            "-5": {"sign_magnitude": "10000101", "ones": "11111010", "twos": "11111011"},
            "0": {"sign_magnitude": "00000000", "ones": "00000000", "twos": "00000000"},
            "20": {"sign_magnitude": "00010100", "ones": "00010100", "twos": "00010100"},
            "-20": {"sign_magnitude": "10010100", "ones": "11101011", "twos": "11101100"},
            "127": {"sign_magnitude": "01111111", "ones": "01111111", "twos": "01111111"},
            "-127": {"sign_magnitude": "11111111", "ones": "10000000", "twos": "10000001"},
            "-128": {"sign_magnitude": None, "ones": None, "twos": "10000000"},
        },
        "roundtrip": {"5": 5, "-5": -5, "-20": -20, "0": 0, "127": 127, "-128": -128},
    }
    return {
        "name": "three_encodings_comparison",
        "summary": "验证 +5/-5/0/+20/-20/+127/-127/-128 的 8 位原码、反码与补码对照及补码编解码往返",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_modular_arithmetic_and_sign_mag_flaw():
    # Sign-magnitude raw addition flaw: +5 (00000101) + -3 (10000011) = 10001000 (-8 in sign-magnitude)
    sm_plus5 = 0b00000101
    sm_minus3 = 0b10000011
    sm_raw_sum = format((sm_plus5 + sm_minus3) & 0xFF, "08b")
    sm_interpreted = -int(sm_raw_sum[1:], 2) if sm_raw_sum[0] == "1" else int(sm_raw_sum[1:], 2)

    # Two's complement mod 256 addition: +5 (00000101) + -3 (11111101) = 1_00000010 -> low 8 bits 00000010 (+2)
    tc_plus5 = int(to_twos_complement(5, 8), 2)
    tc_minus3 = int(to_twos_complement(-3, 8), 2)
    raw_9bit = tc_plus5 + tc_minus3
    low_8bit = format(raw_9bit & 0xFF, "08b")
    carry_out = raw_9bit >> 8

    # Negative weight of MSB in 8-bit two's complement
    weights = [-128, 64, 32, 16, 8, 4, 2, 1]
    minus1_val = sum(w * 1 for w in weights)
    actual = {
        "sm_raw_sum": sm_raw_sum,
        "sm_interpreted": sm_interpreted,
        "tc_raw_9bit": raw_9bit,
        "tc_carry_out": carry_out,
        "tc_low_8bit": low_8bit,
        "tc_decoded": from_twos_complement(low_8bit),
        "weights_minus1": minus1_val,
    }
    expected = {
        "sm_raw_sum": "10001000",
        "sm_interpreted": -8,
        "tc_raw_9bit": 258,
        "tc_carry_out": 1,
        "tc_low_8bit": "00000010",
        "tc_decoded": 2,
        "weights_minus1": -1,
    }
    return {
        "name": "modular_arithmetic_and_sign_mag_flaw",
        "summary": "对比原码直接相加错误(5+(-3)得-8)与补码模 256 加法(258 mod 256 = 2)及最高位负权重 -128",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_four_bit_complement_ring():
    ring = {i: (format(i, "04b"), from_twos_complement(format(i, "04b"))) for i in range(16)}
    # 7 + 1 mod 16 -> 8 -> 1000 -> -8
    wrap_pos = from_twos_complement(format((7 + 1) & 0xF, "04b"))
    # -1 (1111) + 1 mod 16 -> 0000 -> 0
    wrap_neg = from_twos_complement(format((0b1111 + 1) & 0xF, "04b"))
    actual = {
        "ring_size": len(ring),
        "minus_3_bits": to_twos_complement(-3, 4),
        "minus_3_unsigned": int(to_twos_complement(-3, 4), 2),
        "7_plus_1_mod16": wrap_pos,
        "minus1_plus_1_mod16": wrap_neg,
        "min_val": min(v for _, v in ring.values()),
        "max_val": max(v for _, v in ring.values()),
    }
    expected = {
        "ring_size": 16,
        "minus_3_bits": "1101",
        "minus_3_unsigned": 13,
        "7_plus_1_mod16": -8,
        "minus1_plus_1_mod16": 0,
        "min_val": -8,
        "max_val": 7,
    }
    return {
        "name": "four_bit_complement_ring",
        "summary": "构建 4 位补码模 16 环形映射(-8..7),验证 -3 对应 1101(无符号 13) 以及 7+1→-8、-1+1→0 回绕",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_overflow_and_zero_uniqueness():
    def add_8bit_signed(a: int, b: int) -> dict:
        ua = a & 0xFF
        ub = b & 0xFF
        res_u = (ua + ub) & 0xFF
        res_s = res_u - 256 if res_u >= 128 else res_u
        overflow = (a > 0 and b > 0 and res_s < 0) or (a < 0 and b < 0 and res_s >= 0)
        return {"bits": format(res_u, "08b"), "signed": res_s, "overflow": overflow}

    # Negating 0 in 8-bit two's complement: (~0 + 1) & 0xFF == 0
    neg_zero_bits = format(((~0) + 1) & 0xFF, "08b")
    # Negating -128 (0x80) in 8-bit two's complement: (~0x80 + 1) & 0xFF == 0x80 (-128)
    neg_min_bits = format(((~0x80) + 1) & 0xFF, "08b")
    actual = {
        "127_plus_1": add_8bit_signed(127, 1),
        "minus128_plus_minus1": add_8bit_signed(-128, -1),
        "50_plus_40": add_8bit_signed(50, 40),
        "neg_zero_bits": neg_zero_bits,
        "neg_minus128_bits": neg_min_bits,
        "neg_minus128_val": from_twos_complement(neg_min_bits),
    }
    expected = {
        "127_plus_1": {"bits": "10000000", "signed": -128, "overflow": True},
        "minus128_plus_minus1": {"bits": "01111111", "signed": 127, "overflow": True},
        "50_plus_40": {"bits": "01011010", "signed": 90, "overflow": False},
        "neg_zero_bits": "00000000",
        "neg_minus128_bits": "10000000",
        "neg_minus128_val": -128,
    }
    return {
        "name": "overflow_and_zero_uniqueness",
        "summary": "验证 8 位有符号加法溢出判定(127+1→-128)、补码唯一零表示及 -128 取反加 1 仍为 -128",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_three_encodings_comparison(),
        case_modular_arithmetic_and_sign_mag_flaw(),
        case_four_bit_complement_ring(),
        case_overflow_and_zero_uniqueness(),
    ]
    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-negative-numbers-complement-lab/explore-negative-numbers-complement.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-negative-numbers-complement.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线计算机组成原理数值计算、逻辑门电路与体系结构仿真验证器(未在真实浏览器中执行来源交互脚本,也未连接外部网络)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:计算机组成原理

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2634.zip

下载课程关联工程包:计算机组成原理

课程关联工程包(登记关联22章) · 含当前章节或实例 · mbskycom202612a2616.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习