原码

来自GSXAB的知识库
原码
术语名称 原码
英语名称 sign–magnitude
别名 sign-and-magnitude, signed magnitude

原码(sign–magnitude)是一种计算机内的有符号整数表示方法(机器数)。在原码中 [math]\displaystyle{ n }[/math]二进制位中的最高位(most significant bit, MSB)被留作符号位(sign bit),剩下的 [math]\displaystyle{ (n-1) }[/math] 位用于容纳包含 0 在内的各 [math]\displaystyle{ 2^{n-1} }[/math] 个数,并直接使用绝对值二进制表示。

定义

原码(sign–magnitude)指用 [math]\displaystyle{ n }[/math] 位二进制位构成的机器数表示有符号数的方法,其中将其最高位留作符号位,剩余 [math]\displaystyle{ (n-1) }[/math] 位作为绝对值部分:

  • 符号位取 0 时表示符号为 + ,符号位取 1 时表示符号为 - 。
  • 绝对值部分取值表示数有相同的绝对值。

具体对应:

  • [math]\displaystyle{ 0;00\cdots0 }[/math][math]\displaystyle{ 0;11\cdots1 }[/math] 对应 [math]\displaystyle{ +0 }[/math][math]\displaystyle{ +2^{n-1}-1 }[/math]
  • [math]\displaystyle{ 1;00\cdots0 }[/math][math]\displaystyle{ 0;11\cdots1 }[/math] 对应 [math]\displaystyle{ -0 }[/math][math]\displaystyle{ -(2^{n-1}-1) }[/math]

注意:原码表示中,存在 [math]\displaystyle{ 0;00\cdots0 }[/math][math]\displaystyle{ 1;00\cdots0 }[/math] 两个机器数,其真值分别是 [math]\displaystyle{ +0 }[/math][math]\displaystyle{ -0 }[/math] 。因此, [math]\displaystyle{ 2^n }[/math] 个数所对应的真值只有 [math]\displaystyle{ (2^n-1) }[/math] 个不同的,真值范围为 [math]\displaystyle{ -(2^{n-1}-1), \cdots, 2^{n-1}-1 }[/math]

相关计算

如果只用原码,不借助其他表示,进行加减法运算时,原码类似人类计算,需要判断符号位才能确定绝对值部分要进行的实际加减运算,而且需要决策减法的大小关系才能确认顺序。因此直接的加减法较为困难,一般不用在计算。


数的内部表示
十进制数的二进制编码 BCDGray 码奇偶校验码 、 字符表示
有符号整数的机器数 原码反码补码移码
有符号小数的机器数 定点数浮点数IEEE 754