Sol*_*Dia 5 binary proof twos-complement
众所周知,内存中的负数通常表示为二进制补码
from x to ~x + 1
Run Code Online (Sandbox Code Playgroud)
为了回来,我们不会做明显的事情,比如
~([~x + 1] - 1)
Run Code Online (Sandbox Code Playgroud)
但我们这样做
~[~x + 1] + 1
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么它总是有效吗?我想我可以用 1 位、2 位、3 位数字来证明它,然后使用数学归纳法,但这并不能帮助我理解它究竟是如何工作的。
谢谢!
反正都是一样的。也就是说,~x + 1 == ~(x - 1)。但让我们暂时把它放在一边。
f(x) = ~x + 1是它自己的逆。证明:
~(~x + 1) + 1 =
(definition of subtraction: a - b = ~(~a + b))
x - 1 + 1 =
(you know this step)
x
Run Code Online (Sandbox Code Playgroud)
还有,~x + 1 == ~(x - 1)。为什么?好,
~(x - 1) =
(definition of subtraction: a - b = ~(~a + b))
~(~(~x + 1)) =
(remove double negation)
~x + 1
Run Code Online (Sandbox Code Playgroud)
那个(有点不寻常的)减法定义,a - b = ~(~a + b)?
~(~a + b) =
(use definition of two's complement, ~x = -x - 1)
-(~a + b) - 1 =
(move the 1)
-(~a + b + 1) =
(use definition of two's complement, ~x = -x - 1)
-(-a + b) =
(you know this step)
a - b
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
571 次 |
| 最近记录: |