解释为什么x ===〜(〜x + 1)+1(二进制补码并返回!) [英] Explain why x == ~(~x + 1) + 1 (two's complement and back!)

查看:108
本文介绍了解释为什么x ===〜(〜x + 1)+1(二进制补码并返回!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,内存中的负数通常表示为这样的二进制补码

As we all know usually negative numbers in memory represents as two's complement numbers like that

from x to ~x + 1

要获得回报,我们不会做显而易见的事情

and to get back we don't do the obvious thing like

~([~x + 1] - 1)

但相反,我们这样做

~[~x + 1] + 1

有人可以解释为什么它总是可以工作吗?我想我可以用1位,2位,3位数字来证明它,然后使用数学归纳法,但这并不能帮助我理解它的确切工作原理.

can someone explain why does it always work? I think I can proof it with 1-bit, 2-bit, 3-bit numbers and then use Mathematical induction but it doesn't help me understand how exactly that works.

谢谢!

推荐答案

那还是一样.即~x + 1 == ~(x - 1).但是,让我们暂时将其搁置一旁.

That's the same thing anyway. That is, ~x + 1 == ~(x - 1). But let's put that aside for now.

f(x) = ~x + 1是其自身的逆.证明:

f(x) = ~x + 1 is its own inverse. Proof:

~(~x + 1) + 1 =
(definition of subtraction: a - b = ~(~a + b))
x - 1 + 1 =
(you know this step)
x

也,~x + 1 == ~(x - 1).为什么?好吧,

~(x - 1) =
(definition of subtraction: a - b = ~(~a + b))
~(~(~x + 1)) =
(remove double negation)
~x + 1


那减法的定义(有点不寻常),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

这篇关于解释为什么x ===〜(〜x + 1)+1(二进制补码并返回!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆