我只是好奇,为了在二进制中表示-1,是否有一个原因,使用了2的补码:翻转位并加1?
-1由11111111(2的补码)表示,而不是(对我来说更直观)10000001,10000001是二进制1,第一位为负标志。
免责声明:我的工作不依赖二进制算术!
我只是好奇,为了在二进制中表示-1,是否有一个原因,使用了2的补码:翻转位并加1?
-1由11111111(2的补码)表示,而不是(对我来说更直观)10000001,10000001是二进制1,第一位为负标志。
免责声明:我的工作不依赖二进制算术!
当前回答
为什么用Two2的补语系统来表示负数,而不是用One的补语系统,一个令人满意的答案是 二的补语系统解决了一的补语系统中存在的表示负数的0的多重表示和对进位的需要。
欲了解更多信息,请访问https://en.wikipedia.org/wiki/Signed_number_representations
用于末端绕行访问 https://en.wikipedia.org/wiki/End-around_carry
其他回答
尽管这个问题已经很老了,但还是让我说说我的看法。
在我解释这个之前,让我们回到基础上来。2'补码等于1'补码+ 1。 那么1的补是什么,它的加法意义是什么。
任何n位数和它的1的补数的和给出了可以用这n位表示的最大可能的数。 例子:
0010 (2 in 4 bit system)
+1101 (1's complement of 2)
___________________________
1111 (the highest number that we can represent by 4 bits)
现在如果我们尝试在结果中再加1会发生什么。这将导致溢出。
结果将是1 000,即0(因为我们处理的是4位数字,(左边的1是溢出)
So ,
Any n-bit number + its 1's complement = max n-bit number
Any n-bit number + its 1'complement + 1 = 0 ( as explained above, overflow will occur as we are adding 1 to max n-bit number)
于是有人决定把1的补体+ 1称为2'补体。所以上面的表述变成: 任何n位数+它的2的补= 0 也就是说2对一个数的补= -(该数的补)
所有这一切又产生了一个问题,为什么我们只能使用n位中的(n-1)来表示正数,为什么最左边的第n位表示符号(最左边的0表示+ve个数字,1表示-ve个数字)。例如,为什么我们在Java中只使用int的前31位来表示正数,如果第32位是1,它是-ve数。
1100 (lets assume 12 in 4 bit system)
+0100(2's complement of 12)
___________________________
1 0000(结果为0,进位1溢出)
因此(n + 2'补n) = 0的方程组仍然成立。这里唯一的歧义是2对12的补码是0100,它也模糊地表示+8,而不是在2s补码系统中表示-12。
如果正数的最左边总是有一个0,这个问题就可以解决了。在这种情况下,它们的2的补位总是在最左边有一个1,我们就不会有相同的位集表示2的补位数和+ve数的模糊性。
为什么用Two2的补语系统来表示负数,而不是用One的补语系统,一个令人满意的答案是 二的补语系统解决了一的补语系统中存在的表示负数的0的多重表示和对进位的需要。
欲了解更多信息,请访问https://en.wikipedia.org/wiki/Signed_number_representations
用于末端绕行访问 https://en.wikipedia.org/wiki/End-around_carry
维基百科说明了一切:
二补系统的优点是不需要加减电路检查操作数的符号来决定是加还是减。这一特性使系统实现更简单,能够轻松地处理更高精度的算术。此外,零只有一种表示,避免了与负零相关的微妙之处,这种微妙之处存在于补体系统中。
换句话说,无论数字是否为负,加法都是一样的。
2的补数允许以正常的方式进行加减法(就像对无符号数字进行绕线运算一样)。它还防止了-0(一种单独的表示0的方法,如果使用常规的逐位比较数字的方法,它将不等于0)。
It's worthwhile to note that on some early adding machines, before the days of digital computers, subtraction would be performed by having the operator enter values using a different colored set of legends on each key (so each key would enter nine minus the number to be subtracted), and press a special button would would assume a carry into a calculation. Thus, on a six-digit machine, to subtract 1234 from a value, the operator would hit keys that would normally indicate "998,765" and hit a button to add that value plus one to the calculation in progress. Two's complement arithmetic is simply the binary equivalent of that earlier "ten's-complement" arithmetic.