我在上一门计算机系统课程,在某种程度上,我一直在为“二的补充”而挣扎。我想了解它,但我所读到的一切并没有让我明白它的含义。我读过维基百科的文章和其他各种文章,包括我的课本。

什么是2的补数,我们如何使用它,它如何在强制转换(从有符号到无符号,反之亦然)、逐位操作和位移位操作等操作中影响数字?


当前回答

到目前为止,许多答案都很好地解释了为什么2的补数被用来表示负数,但没有告诉我们2的补数是什么,尤其是没有告诉我们为什么加了一个“1”,而且实际上经常以错误的方式加。

这种混淆来自于对补数定义的不理解。补语是指使某物完整的缺失部分。

根据定义,n位数x以b为基数的基数补是b^n-x。

在二进制中,4由100表示,它有3位数字(n=3)和基数2 (b=2)。所以它的基数补是b^n-x = 2^3-4=8-4=4(或二进制的100)。

然而,在二进制中,求一个基数的补并不像求它的消简基数补那么容易,消简基数补定义为(b^n-1)-y,只比基数补小1。要得到一个减少的基数补,只需翻转所有的数字。

100 -> 011(减基数补位)

为了得到基数(2的)补,我们只需按定义加1。

011 +1 ->100(2的补码)。

现在,有了这个新的理解,让我们看看Vincent Ramdhanie给出的例子(见上面的第二个回答):

将1111转换为十进制: 这个数从1开始,所以它是负的,所以我们找到1111的补数,也就是0000。 0000加上1,得到0001。 将0001转换为十进制,即1。 应用符号= -1。 大作。

应理解为:

数字从1开始,所以是负的。所以我们知道它是x的一个2的补。为了找到由它的2的补表示的x,我们首先需要找到它的1的补。

x的2的补数是1111 x的补数:1111-1 ->1110; X = 0001,(翻转所有数字)

应用符号-,结果=-x =-1。

其他回答

这是一种对负整数进行编码的聪明方法,该方法将数据类型中大约一半的位组合保留给负整数,并且将大多数负整数与其对应的正整数相加会导致进位溢出,使结果为二进制零。

因此,在2的补码中,如果1是0x0001,那么-1是0x1111,因为这将导致0x0000的组合和(溢出1)。

我喜欢lavinio的回答,但变换部分增加了一些复杂性。通常情况下,可以选择在保留符号位的情况下移动位,或者不保留符号位。这是将数字处理为有符号数字(-8到7表示小块,-128到127表示字节)或全范围无符号数字(0到15表示小块,0到255表示字节)之间的选择。

2's complement is essentially a way of coming up with the additive inverse of a binary number. Ask yourself this: Given a number in binary form (present at a fixed length memory location), what bit pattern, when added to the original number (at the fixed length memory location), would make the result all zeros ? (at the same fixed length memory location). If we could come up with this bit pattern then that bit pattern would be the -ve representation (additive inverse) of the original number; as by definition adding a number to its additive inverse always results in zero. Example: take 5 which is 101 present inside a single 8 bit byte. Now the task is to come up with a bit pattern which when added to the given bit pattern (00000101) would result in all zeros at the memory location which is used to hold this 5 i.e. all 8 bits of the byte should be zero. To do that, start from the right most bit of 101 and for each individual bit, again ask the same question: What bit should I add to the current bit to make the result zero ? continue doing that taking in account the usual carry over. After we are done with the 3 right most places (the digits that define the original number without regard to the leading zeros) the last carry goes in the bit pattern of the additive inverse. Furthermore, since we are holding in the original number in a single 8 bit byte, all other leading bits in the additive inverse should also be 1's so that (and this is important) when the computer adds "the number" (represented using the 8 bit pattern) and its additive inverse using "that" storage type (a byte) the result in that byte would be all zeros.

 1 1 1
 ----------
   1 0 1
 1 0 1 1 ---> additive inverse
  ---------
   0 0 0

问题是“什么是“2的补码”?”

对于那些想要从理论上理解它的人(以及我试图补充其他更实际的答案),简单的答案是:2的补码是对偶系统中不需要额外字符(如+和-)的负整数的表示。

最简单的答案:

1111 + 1 =(1)0000。所以1111一定是-1。那么-1 + 1 = 0。

理解这些对我来说是完美的。