为什么二进制补码在处理大数时仍然有效?
Why does two's complement still work when working with large numbers?
我最近在阅读二进制补码并注意到,当处理非常接近极限的无符号整数时(大多数数字大到 MSB 为 1),减法似乎仍然有效,即使有符号位应该仍然填写实际号码信息。例如,取254和252,在8位中分别表示为0b11111110
和0b11111100
。减法将取 252 的 2 的补码,因此 0b11111110 + 0b00000100
给出正确的结果 0b00000010 = 2
。为什么这会按预期工作?
PS.: 我确实也注意到,如果我要取无符号数并将它们视为二进制补码形式,我会得到 -2 和 -4,这做减去 2。这可能是系统如何建立并最终被设计使用的结果吗?
继 John Filleau 的评论后:
If the two's complement of an 8 bit number N
is (256 - N)
, and if 8 bit addition and subtraction is modulo 256, that is N1 - N2 = (N1 - N2)%256
. If you replace subtraction of N2
with addition of its two's complement, you get (N1 - N2) = (N1 + (256 - N2))%256
. Modulo operation is distributive, and 256%256 = 0
, so you find that for any values of N1 and N2, adding the two's complement of N2
is equivalent to subtracting N2
.
我在分析这个操作时的主要错误是(除了忽略值换行的事实)假设计算机需要将无符号整数转换为有符号整数来执行减法运算,如上所示,这不是必然如此。补码的概念适用于无符号数和有符号数。
我最近在阅读二进制补码并注意到,当处理非常接近极限的无符号整数时(大多数数字大到 MSB 为 1),减法似乎仍然有效,即使有符号位应该仍然填写实际号码信息。例如,取254和252,在8位中分别表示为0b11111110
和0b11111100
。减法将取 252 的 2 的补码,因此 0b11111110 + 0b00000100
给出正确的结果 0b00000010 = 2
。为什么这会按预期工作?
PS.: 我确实也注意到,如果我要取无符号数并将它们视为二进制补码形式,我会得到 -2 和 -4,这做减去 2。这可能是系统如何建立并最终被设计使用的结果吗?
继 John Filleau 的评论后:
If the two's complement of an 8 bit number
N
is(256 - N)
, and if 8 bit addition and subtraction is modulo 256, that isN1 - N2 = (N1 - N2)%256
. If you replace subtraction ofN2
with addition of its two's complement, you get(N1 - N2) = (N1 + (256 - N2))%256
. Modulo operation is distributive, and256%256 = 0
, so you find that for any values of N1 and N2, adding the two's complement ofN2
is equivalent to subtractingN2
.
我在分析这个操作时的主要错误是(除了忽略值换行的事实)假设计算机需要将无符号整数转换为有符号整数来执行减法运算,如上所示,这不是必然如此。补码的概念适用于无符号数和有符号数。