如何证明C语句-x,〜x + 1和〜(x-1)产生相同的结果? [英] How to prove that the C statement -x, ~x+1, and ~(x-1) yield the same results?

查看:72
本文介绍了如何证明C语句-x,〜x + 1和〜(x-1)产生相同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这句话背后的逻辑,即证明.对于任何x,C表达式-x,〜x + 1和〜(x-1)都产生相同的结果.对于特定示例,我可以证明这是正确的.我认为证明这一点的方式与二进制补码的性质有关.有任何想法吗?

I want to know the logic behind this statement, the proof. The C expression -x, ~x+1, and ~(x-1) all yield the same results for any x. I can show this is true for specific examples. I think the way to prove this has something to do with the properties of two's complement. Any ideas?

推荐答案

请考虑将数字按位补码时所得到的结果.n位整数x的按位补码在所有x都为0的地方都为1,反之亦然.因此很明显可以看到:

Consider what you get when you add a number to its bitwise complement. The bitwise complement of an n-bit integer x has a 1 everywhere x has a 0, and vice versa. So it's clear to see:

x +〜x = 0b11 ... 11(全1的n位值)

x + ~x = 0b11...11 (n-bit value of all ones)

无论x中的位数如何.此外,请注意,在一个全为1的n位数字上加一个将使其换为零.因此,我们看到:

Regardless of the number of bits in x. Further, note that adding one to an n-bit number filled with all ones will make it wrap to zero. Thus we see:

x +〜x + 1 = 0b11 ... 11 + 1 = 0和〜x +1 = -x.

x + ~x + 1 = 0b11...11 + 1 = 0 and ~x + 1 = -x.

类似地,注意(x-1)+〜(x-1)= 0b11 ... 11.然后(x-1)+〜(x-1)+1 = 0,〜(x-1)= -x.

Similarly, note (x - 1) + ~(x - 1) = 0b11...11. Then (x - 1) + ~(x - 1) + 1 = 0, and ~(x - 1) = -x.

这篇关于如何证明C语句-x,〜x + 1和〜(x-1)产生相同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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