我只是好奇,为了在二进制中表示-1,是否有一个原因,使用了2的补码:翻转位并加1?
-1由11111111(2的补码)表示,而不是(对我来说更直观)10000001,10000001是二进制1,第一位为负标志。
免责声明:我的工作不依赖二进制算术!
我只是好奇,为了在二进制中表示-1,是否有一个原因,使用了2的补码:翻转位并加1?
-1由11111111(2的补码)表示,而不是(对我来说更直观)10000001,10000001是二进制1,第一位为负标志。
免责声明:我的工作不依赖二进制算术!
当前回答
用补法执行减法的优点是减少了硬件 的复杂性。不需要不同的数字电路来进行加减法运算 加法和减法只能由加法器执行。
其他回答
这是为了简化数字的和和和差。2的补数中一个负数和一个正数的和与正常方式的和是一样的。
A major advantage of two's-complement representation which hasn't yet been mentioned here is that the lower bits of a two's-complement sum, difference, or product are dependent only upon the corresponding bits of the operands. The reason that the 8 bit signed value for -1 is 11111111 is that subtracting any integer whose lowest 8 bits are 00000001 from any other integer whose lowest 8 bits are 0000000 will yield an integer whose lowest 8 bits are 11111111. Mathematically, the value -1 would be an infinite string of 1's, but all values within the range of a particular integer type will either be all 1's or all 0's past a certain point, so it's convenient for computers to "sign-extend" the most significant bit of a number as though it represented an infinite number of 1's or 0's.
Two's-complement is just about the only signed-number representation that works well when dealing with types larger than a binary machine's natural word size, since when performing addition or subtraction, code can fetch the lowest chunk of each operand, compute the lowest chunk of the result, and store that, then load the next chunk of each operand, compute the next chunk of the result, and store that, etc. Thus, even a processor which requires all additions and subtractions to go through a single 8-bit register can handle 32-bit signed numbers reasonably efficiently (slower than with a 32-bit register, of course, but still workable).
当使用C标准所允许的任何其他有符号表示时,结果的每一位都可能受到操作数的任何位的影响,这就需要将整个值一次保存在寄存器中,或者在计算之后进行额外的步骤,至少在某些情况下,需要读取、修改和重写结果的每个块。
使用2的补码是因为它更容易在电路中实现,也不允许负零。
如果有x位,2的补码范围从+(2^x/2+1)到-(2^x/2)。补码将从+(2^x/2)到-(2^x/2),但允许负数为零(0000在4位1的补码系统中等于1000)。
维基百科说明了一切:
二补系统的优点是不需要加减电路检查操作数的符号来决定是加还是减。这一特性使系统实现更简单,能够轻松地处理更高精度的算术。此外,零只有一种表示,避免了与负零相关的微妙之处,这种微妙之处存在于补体系统中。
换句话说,无论数字是否为负,加法都是一样的。
2的补语允许负数和正数相加,而不需要任何特殊的逻辑。
如果你想用你的方法做1和-1相加 10000001 (1) + 00000001 (1) 你得到 10000010 (2)
相反,通过使用2的补数,我们可以相加
11111111 (1) + 00000001 (1) 你得到 00000000 (0)
减法也是如此。
同样,如果你试着用6减去4(两个正数),你可以用2补4,然后把两者相加6 + (-4)= 6 -4 = 2
这意味着正数和负数的减法和加法都可以由cpu中的同一个电路完成。