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

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


当前回答

简单来说,2的补码是一种在计算机内存中存储负数的方法。而正数则存储为普通二进制数。

让我们考虑这个例子,

计算机使用二进制数字系统来表示任何数字。

x = 5;

这表示为0101。

x = -5;

当计算机遇到-号时,它会计算出它的2的补数并存储它。

也就是说,5 = 0101,它的2的补是1011。

计算机处理数字的重要规则是,

如果第一位是1,那么它一定是负数。 如果除第1位之外的所有位都是0,那么它就是一个正数,因为在数字系统中没有-0(1000不是-0,而是正8)。 如果所有的位都是0,那么它就是0。 否则就是正数。

其他回答

2的补码是表示负数的一种方式,大多数控制器和处理器都以2的补码形式存储负数。

2的补码对于查找二进制值非常有用,但是我想到了一个更简洁的方法来解决这样的问题(从未见过其他人发布它):

以二进制为例:1101(假设空格“1”是符号)等于-3。

使用2的补码,我们可以这样做…翻1101到0010…加上0001 + 0010 ===>得到0011。0011的正二进制= 3。因此1101 = -3!

我意识到:

而不是所有的翻转和加法,你可以只做一个基本的方法来解决正二进制(假设0101)是(23 * 0)+(22 * 1)+(21 * 0)+(20 * 1)= 5。

用否定句做同样的概念!(稍微扭曲一下)

以1101为例:

对于第一个数字,用-(23 * 1)= -8代替23 * 1 = 8。

然后像往常一样,做-8 + (22 * 1)+ (21 * 0)+ (20 * 1)= -3

最简单的答案:

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

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

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的补码中,如果1是0x0001,那么-1是0x1111,因为这将导致0x0000的组合和(溢出1)。