移码

来自GSXAB的知识库
移码
术语名称 移码
英语名称 offset binary
别名 biases representation, excess code

移码(offset binary)是一种计算机内的定点整数表示方法(机器数)。在移码中,全部的数都被加上一个基准偏移值,这个偏移值是一个根据场景限制选择的固定整数,保证要表示的负数都在相加后变成某个范围内的数(通常是无符号数范围),然后按照偏移过的数表示为二进制。

定义

移码(offset binary)指用 [math]\displaystyle{ n }[/math] 位二进制位构成的机器数表示有符号数的方法,其中将所有要表示的数增加一定的偏移量。在 [math]\displaystyle{ n }[/math] 位时这一偏移量默认取 [math]\displaystyle{ 2^{n-1} }[/math] ,也就是使得 [math]\displaystyle{ -2^{n-1} }[/math][math]\displaystyle{ 2^{n-1}-1 }[/math] 的范围偏移到可以直接表示的范围。

integer_offset_binary.svg

具体对应:

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

注意:以上是移码通常的偏移量选择,但这不是固定情况。对于特殊场景,比如全 0 的位置无法使用需要空出来的情况,偏移量会变成保证 0…01 表示数落在可用范围内,这个见 IEEE 754

integer_offset_binary_range.svg

注意:与原码移码补码方法均不同,补码因为有偏移值,不会把全 0 的数字对应到 0 。

移码运算

将机器数表示本身视为二进制数,则可以认为从数本身到机器数的映射关系为:

[math]\displaystyle{ x \mapsto x+2^{n-1} }[/math]

可以看到移码就是补码减去 [math]\displaystyle{ 2^{n-1} }[/math] 的结果,这一点也可以作为相关运算的基准。

移码相反数

[math]\displaystyle{ x'=x+2^{n-1} \Rightarrow (-x)'=-x+2^{n-1} \Rightarrow (-x)'=2^n - x' }[/math]

移码加减法

[math]\displaystyle{ a'=a+2^{n-1}, b'=b+2^{n-1} \Rightarrow (a+b)' = a+b+2^{n-1} = a'+b'-2^{n-1} }[/math]


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