我只是好奇,为了在二进制中表示-1,是否有一个原因,使用了2的补码:翻转位并加1?

-1由11111111(2的补码)表示,而不是(对我来说更直观)10000001,10000001是二进制1,第一位为负标志。

免责声明:我的工作不依赖二进制算术!


当前回答

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标准所允许的任何其他有符号表示时,结果的每一位都可能受到操作数的任何位的影响,这就需要将整个值一次保存在寄存器中,或者在计算之后进行额外的步骤,至少在某些情况下,需要读取、修改和重写结果的每个块。

其他回答

该操作的通常实现是“翻转位并加1”,但有另一种定义它的方式可能使其原理更清楚。2的补数是通常的无符号表示形式,其中每一位控制2的下一次方,并使最有效项为负。

取8位值a7 a6 a5 a4 a3 a2 a1 a0

通常的无符号二进制解释是: 27*a7 + 26*a6 + 25*a5 + 24*a4 + 23*a3 + 22*a2 + 21*a1 + 20*a0 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255

两人的补充解释是: -27*a7 + 26*a6 + 25*a5 + 24*a4 + 23*a3 + 22*a2 + 21*a1 + 20*a0 = -128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = -1

其他任何位都不会改变含义,并且进位到a7是“溢出”,不期望工作,所以几乎所有的算术操作都可以工作而不需要修改(正如其他人所注意到的)。符号大小通常检查符号位,并使用不同的逻辑。

扩展一下其他的答案:

在two's complement中

加法与普通正整数加法的原理相同。 减法也不会变 乘法!

"组织"需要不同的机制。

所有这些都是正确的,因为2的补是普通的模算术,我们选择通过减去模来看待一些负数。

有不同类型的表示,它们是:

无符号数表示 有符号数字表示 补体表示 二补体表示法

无符号数字表示,仅用于表示正数

有符号的数字表示,用来表示正数和负数。在有符号数表示中,MSB位表示符号位,其余位表示数字。当MSB为0时表示数字为正,当MSB为1时表示数字为负。

有符号数表示的问题是0有两个值。

补码表示法的问题是0有两个值。

但如果我们使用2的补体表示,那么0就只有一个值,这就是为什么我们用2的补体形式表示负数。

来源:负数为什么以二进制补码形式存储

为什么用Two2的补语系统来表示负数,而不是用One的补语系统,一个令人满意的答案是 二的补语系统解决了一的补语系统中存在的表示负数的0的多重表示和对进位的需要。

欲了解更多信息,请访问https://en.wikipedia.org/wiki/Signed_number_representations

用于末端绕行访问 https://en.wikipedia.org/wiki/End-around_carry

2的补数允许以正常的方式进行加减法(就像对无符号数字进行绕线运算一样)。它还防止了-0(一种单独的表示0的方法,如果使用常规的逐位比较数字的方法,它将不等于0)。