Content deleted Content added
Tags: Reverted Visual edit |
m →Example: HTTP to HTTPS for Cornell University |
||
(27 intermediate revisions by 19 users not shown) | |||
Line 1:
{{Short description|Mathematical operation on binary numbers, and a number representation based on this operation}}
'''Two's complement''' is the
Unlike the [[ones' complement]] scheme, the two's complement scheme has only one representation for zero, with room for one extra negative number (the range of a 4-bit number is -8 to +7). Furthermore, the same arithmetic implementations can be used on signed as well as unsigned integers<ref>
{{cite book
|first1=Alexandre |last1=Bergel
Line 15:
}}
</ref>
and differ only in the integer overflow situations, since the sum of representations of a positive number and its negative is 0 (with the carry bit set).
== Procedure ==
The following is the procedure for obtaining the two's complement representation of a given ''negative'' number in binary digits:
* Step 1: starting with the absolute binary representation of the number, with the leading bit being a sign bit;<ref>{{cite web|url=https://www.rit.edu/academicsuccesscenter/sites/rit.edu.academicsuccesscenter/files/documents/math-handouts/DM3_TwosComplement_BP_9_22_14.pdf|title=Two's Complement|website=University of Rochester Academic Success Center}}</ref>
Line 26:
For example, to calculate the [[decimal]] number '''−6''' in binary from the number '''6''':
* Step 1: ''+6'' in decimal is ''0110'' in binary; the leftmost significant bit (the first 0) is the [[Sign (mathematics)|sign]]
* Step 2: flip all bits in ''0110'', giving ''1001''.
* Step 3: add the place value 1 to the flipped number ''1001'', giving ''1010''.
Line 60:
==Theory==
Two's complement is an example of a [[Method of complements|radix complement]]. The 'two' in the name refers to the
▲The 'two' in the name refers to the term which, expanded fully in an {{mvar|N}}-bit system, is actually "two to the power of N" - {{math|2<sup>''N''</sup>}} (the only case where exactly 'two' would be produced in this term is {{math|''N'' {{=}} 1}}, so for a 1-bit system, but these do not have capacity for both a sign and a zero), and it is only this full term in respect to which the [[method of complements|complement]] is calculated. As such, the precise definition of the ''Two's complement'' of an {{mvar|N}}-bit number is the [[method of complements|complement]] of that number with respect to {{math|2<sup>''N''</sup>}}.
The defining property of being a ''complement to a number with respect to {{math|2<sup>N</sup>}}'' is simply that the summation of this number with the original produce {{math|2<sup>''N''</sup>}}. For example, using binary with numbers up to three
{|class="wikitable sortable floatright" style="text-align: center;"
|+ Three-bit integers
Line 148 ⟶ 147:
| −1
|}
Calculation of the binary two's complement of a positive number essentially means subtracting the number from the {{math|2<sup>''N''</sup>}}. But as can be seen for the three-bit example and the four-bit {{math|1000<sub>2</sub>}} ({{math|2<sup>3</sup>}}), the number {{math|2<sup>''N''</sup>}} will not itself be representable in a system limited to {{mvar|''N''}} bits, as it is just outside the {{mvar|''N''}} bits space (the number is nevertheless the reference point of the "Two's complement" in an {{mvar|''N''}}-bit system). Because of this, systems with maximally {{mvar|''N''}}-bits must break the subtraction into two operations: first subtract from the maximum number in the {{mvar|''N''}}-bit system, that is {{math|2<sup>''N''</sup>
Compared to other systems for representing signed numbers (
==History==
Line 161 ⟶ 160:
The value {{mvar|w}} of an {{mvar|N}}-bit integer <math>a_{N-1} a_{N-2} \dots a_0</math> is given by the following formula:
The most significant bit determines the sign of the number and is sometimes called the [[sign bit]]. Unlike in [[sign-and-magnitude]] representation, the sign bit also has the weight {{math|−(2<sup>''N'' − 1</sup>)}} shown above. Using {{mvar|N}} bits, all integers from {{math|−(2<sup>''N'' − 1</sup>)}} to {{math|2<sup>''N'' − 1</sup> − 1}} can be represented.
==Converting to two's complement representation==
<!-- This section contains one footnote that is wrapped in a <ref></ref> tag, but this footnote does not list any external references or sources. -->
In two's complement notation, a ''non-negative'' number is represented by its ordinary [[Binary numeral system|binary representation]]; in this case, the most significant bit is 0. Though, the range of numbers represented is not the same as with unsigned binary numbers.
The two's complement operation is the [[additive inverse]] operation, so negative numbers are represented by the two's complement of the [[absolute value]].
Line 174 ⟶ 175:
For example, using 1 byte (=8 bits), the decimal number 5 is represented by
The most significant bit (the leftmost bit in this case) is 0, so the pattern represents a non-negative value. To convert to −5 in two's-complement notation, first, all bits are inverted, that is: 0 becomes 1 and 1 becomes 0:
At this point, the representation is the [[ones' complement]] of the decimal value −5. To obtain the two's complement, 1 is added to the result, giving:
The result is a signed binary number representing the decimal value −5 in two's-complement form. The most significant bit is 1,
Alternatively, instead of adding 1 after inverting a positive binary number, 1 can be subtracted from the number ''before'' it is inverted. The two methods can easily be shown to be equivalent. The inversion (ones' complement) of <math>x</math> equals <math>(2^N - 1) - x</math>, so the sum of the inversion and 1 equals <math>(2^N - 1) - x + 1 = </math><math>2^N - x - 1 + 1 = </math><math>2^N - x</math>, which equals the two's complement of <math>x</math> as expected. The inversion of <math>x - 1</math> equals <math>(2^N - 1) - (x - 1) = </math><math>(2^N - 1) - x + 1 = </math><math>2^N - x</math>, identical to the previous equation. Essentially, the subtraction inherent in the inversion operation changes the −1 added to <math>x</math> before the inversion into +1 added after the inversion. This alternate subtract-and-invert algorithm to form a two's complement can sometimes be advantageous in computer programming or hardware design, for example where the subtraction of 1 can be obtained for free by incorporating it into an earlier operation.<ref>... e.g. by reducing an added constant by 1, increasing a subtracted constant by 1, or setting the carry/borrow flag before a subtract-with-borrow operation. For example, to compute <math>-(m + 4)</math>, instead of adding 4 to <math>m</math>, inverting the result, and then adding 1, one can merely add 3 (= 4 − 1) to <math>m</math> and then invert the result. (Of course, it is also an option, using the invert-and-add scheme, to invert <math>m</math> first and then subtract 3 [equivalent to adding −3 = −4 + 1].)</ref>
The two's complement of a negative number is the corresponding positive value, except in the special case of the [[most negative number]]. For example, inverting the bits of −5 (above) gives:
And adding one gives the final value:
The two's complement of the most negative number representable (e.g. a one as the most-significant bit and all other bits zero) is itself. Hence, there is an 'extra' negative number for which two's complement does not give the negation, see {{section link||Most negative number}} below.
The case for the most negative number is one of only two special cases. The other special case is for zero, the two's complement of which is zero: inverting gives all ones, and adding one changes the ones back to zeros (since the overflow is ignored). Mathematically, in the two's complement system of signed integers (which represents the negative of each number as its two's complement), this is obviously correct: the negative of 0 is in fact 0 (<math>-0 = 0</math>). This zero case also makes sense by the definition of two's complements: by that definition, the two's complement of zero would be <math>2^N - 0 = 2^N</math>, but in <math>N</math> bits, all values are taken modulo <math>2^N</math>, and <math>2^N</math>{{math|mod }}<math>2^N = 0</math>. In other words, the two's complement of 0 in <math>N</math> bits is (by definition) a single 1 bit followed by <math>N</math> zeros, but the 1 gets truncated, leaving 0.<ref>Zero is the one value which when added to its two's complement, using machine (modular) binary arithmetic, does not sum to <math>2^N</math>, but observe that in arithmetic modulo <math>2^N</math>, <math>0</math> is congruent to <math>2^N</math>.</ref>
In summary, the two's complement of any number, either positive, negative, or zero, can be computed in the same ways. In two's complement signed integer representation, the two's complement of any integer is equal to -1 times that integer, except for the most negative integer representable in the given number of bits <math>N</math>, i.e. the integer <math>-2^{N-1}</math>, the two's complement of which is itself (still negative).
===Subtraction from 2<sup>''N''</sup>===
Line 194 ⟶ 199:
For example, to find the four-bit representation of −5 (subscripts denote the [[radix|base of the representation]]):
Hence, with {{math|1=''N'' = 4}}:
The calculation can be done entirely in base 10, converting to base 2 at the end:
===Working from LSB towards MSB===
Line 208 ⟶ 213:
{{Main|Sign extension}}
{|class="wikitable floatright" style="margin-left: 1.5em;text-align:center"
|+ Sign-bit repetition in 7- and 8-bit integers using two's complement
|-
Line 215 ⟶ 220:
!8-bit notation
|-
|
|-
|
|}
When turning a two's-complement number with a certain number of bits into one with more bits (e.g., when copying from a one-byte variable to a two-byte variable), the most-significant bit must be repeated in all the extra bits.
Similarly, when a number is shifted to the right, the most-significant bit, which contains the sign information, must be maintained. However, when shifted to the left, a bit is shifted out. These rules preserve the common semantics that left shifts multiply the number by two and right shifts divide the number by two.
Both shifting and doubling the precision are important for some multiplication algorithms. Note that unlike addition and subtraction, width extension and right shifting are done differently for signed and unsigned numbers.
Line 229 ⟶ 234:
With only one exception, starting with any number in two's-complement representation, if all the bits are flipped and 1 added, the two's-complement representation of the negative of that number is obtained. Positive 12 becomes negative 12, positive 5 becomes negative 5, zero becomes zero(+overflow), etc.
{|class="wikitable floatright" style="width:18em;text-align:center"|"
|+ <span class="anchor" id="−128_example_anchor">The two's complement of
|-
|
|-
|-
|-
|colspan="2;"
|}
Taking the two's complement (negation) of the minimum number in the range will not have the desired effect of negating the number. For example, the two's complement of {{math| −128 }} in an eight-bit system is {{math| −128 ,}} as shown in the [[#−128_example_anchor|table to the right]]. Although the expected result from negating {{math| −128 }} is {{math| +128 ,}} there is no representation of {{math| +128 }} with an eight bit two's complement system and thus it is in fact impossible to represent the negation. Note that the two's complement being the same number is detected as an overflow condition since there was a carry into but not out of the most-significant bit.
Having a nonzero number equal to its own negation is forced by the fact that zero is its own negation, and that the total number of numbers is even. Proof: there are {{math| 2^n
The presence of the most negative number can lead to unexpected programming bugs where the result has an unexpected sign, or leads to an unexpected overflow exception, or leads to completely strange behaviors. For example,
* the unary negation operator may not change the sign of a nonzero number. e.g., {{math| −(−128) ⟼ −128 }}
* an implementation of [[absolute value]] may return a negative number;<ref>
{{cite web
Line 254 ⟶ 259:
|url=http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html
}}
</ref>
* Likewise, multiplication by {{math| −1 }} may fail to function as expected; e.g., {{math| (−128) × (−1) ⟼ −128 .}}
Line 261 ⟶ 266:
|first=John |last=Regehr
|year=2013
|title=Nobody expects the Spanish inquisition, or INT_MIN to be divided by
|website=Regehr.org |type=blog
|url=https://blog.regehr.org/archives/887
Line 279 ⟶ 284:
In the [[C (programming language)|C]] and [[C++]] programming languages, the above behaviours are [[Undefined behavior|undefined]] and not only may they return strange results, but the compiler is free to assume that the programmer has ensured that undefined numerical operations never happen, and make inferences from that assumption.<ref name=int32-c/> This enables a number of optimizations, but also leads to a number of strange bugs in programs with these undefined calculations.
This most negative number in two's complement is sometimes called
{{cite report
|first1=Reynald |last1=Affeldt
Line 307 ⟶ 312:
==Why it works==
Given a set of all possible {{mvar|N}}-bit values, we can assign the lower (by the binary value) half to be the integers from 0 to {{math|(2<sup>''N'' − 1</sup> − 1)}} inclusive and the upper half to be {{math|−2<sup>''N'' − 1</sup>}} to −1 inclusive.
| url = http://www.cs.uwm.edu/~cs151/Bacon/Lecture/HTML/ch03s09.html
| title = 3.9. Two's Complement | work = Chapter 3. Data Representation
Line 326 ⟶ 331:
!Binary (8-bit)
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|}
===Example===
For example, an 8 bit number can only represent every integer from
<div style="overflow-x: auto;">
<pre style="width:25em">
1111 1111 255.
Line 361 ⟶ 368:
1010 0001 (two's complement) 161.
</pre>
</div>
{|class="wikitable floatright" style="width:14em;"▼
▲{|class="wikitable floatright" style="width:14em;text-align:center"
|+ Two's complement 4 bit integer values
!Two's complement
!Decimal
|-
|-
|-
|-
|-
|-
|-
|-
|-
|-
|-
|-
|-
|-
|-
|-
|}
Fundamentally, the system represents negative integers by counting backward and [[modular arithmetic|wrapping around]]. The boundary between positive and negative numbers is arbitrary, but by [[Convention (norm)|convention]] all negative numbers have a left-most bit ([[most significant bit]]) of one. Therefore, the most positive four-bit number is 0111 (7.) and the most negative is 1000 (
|first=Thomas |last=Finley
|date=April 2000
|title=Two's Complement
|series=Class notes for CS 104
|publisher=Cornell University |department=Computer Science |place=Ithaca,
|url=
}}</ref>
The system is useful in simplifying the implementation of arithmetic on computer hardware. Adding 0011 (3.) to 1111 (
The system therefore allows addition of negative operands without a subtraction circuit or a circuit that detects the sign of a number. Moreover, that addition circuit can also perform subtraction by taking the two's complement of a number (see below), which only requires an additional cycle or its own adder circuit. To perform this, the circuit merely operates as if there were an extra left-most bit of 1.
Line 415 ⟶ 424:
===Addition===
Adding two's complement numbers requires no special processing even if the operands have opposite signs; the sign of the result is determined automatically.
<pre style="width:25em">▼
<div style="overflow-x: auto;">
▲<pre style="width:25em;">
0000 1111 (15)
+ 1111 1011 (−5)
Line 422 ⟶ 433:
0000 1010 (10)
</pre>
</div>
Or the computation of 5 − 15 = 5 + (−15):
<div style="overflow-x: auto;">
<pre style="width:25em">
0000 0101 ( 5)
Line 431 ⟶ 444:
1111 0110 (−10)
</pre>
</div>
This process depends upon restricting to 8 bits of precision; a carry to the (nonexistent) 9th most significant bit is ignored, resulting in the arithmetically correct result of 10<sub>10</sub>.
The last two bits of the [[Carry flag|carry]] row (reading right-to-left) contain vital information: whether the calculation resulted in an [[arithmetic overflow]], a number too large for the binary system to represent (in this case greater than 8 bits).
In other terms, if the left two carry bits (the ones on the far left of the top row in these examples) are both 1s or both 0s, the result is valid; if the left two carry bits are "1 0" or "0 1", a sign overflow has occurred.
<div style="overflow-x: auto;">
<pre style="width:25em">
0111 (carry)
Line 444 ⟶ 460:
1010 (−6) invalid!
</pre>
</div>
In this case, the far left two (MSB) carry bits are "01", which means there was a two's-complement addition overflow. That is, 1010<sub>2</sub> = 10<sub>10</sub> is outside the permitted range of −8 to 7. The result would be correct if treated as unsigned integer.▼
▲In this case, the far left two (MSB) carry bits are "01", which means there was a two's-complement addition overflow.
In general, any two {{mvar|N}}-bit numbers may be added ''without'' overflow, by first sign-extending both of them to {{math|''N'' + 1}} bits, and then adding as above. The {{math|''N'' + 1}} bits result is large enough to represent any possible sum ({{math|1=''N'' = 5}} two's complement can represent values in the range −16 to 15) so overflow will never occur. It is then possible, if desired, to 'truncate' the result back to {{mvar|N}} bits while preserving the value if and only if the discarded bit is a proper sign extension of the retained result bits. This provides another method of detecting overflow—which is equivalent to the method of comparing the carry bits—but which may be easier to implement in some situations, because it does not require access to the internals of the addition.▼
▲In general, any two {{mvar|N}}-bit numbers may be added ''without'' overflow, by first sign-extending both of them to {{math|''N'' + 1}} bits, and then adding as above. The {{math|''N'' + 1}} bits result is large enough to represent any possible sum ({{math|1=''N'' = 5}} two's complement can represent values in the range
===Subtraction===
Computers usually use the [[method of complements]] to implement subtraction. Using complements for subtraction is closely related to using complements for representing negative numbers, since the combination allows all signs of operands and results; direct subtraction works with two's-complement numbers as well. Like addition, the advantage of using two's complement is the elimination of examining the signs of the operands to determine whether addition or subtraction is needed. For example, subtracting −5 from 15 is really adding 5 to 15, but this is hidden by the two's-complement representation:
<div style="overflow-x: auto;">
<pre style="width:25em">
11110 000 (borrow)
Line 457 ⟶ 477:
0001 0100 (20)
</pre>
</div>
Overflow is detected the same way as for addition, by examining the two leftmost (most significant) bits of the borrows; overflow has occurred if they are different.
Another example is a subtraction operation where the result is negative: 15 − 35 = −20:
<div style="overflow-x: auto;">
<pre style="width:25em">
11100 000 (borrow)
Line 467 ⟶ 491:
1110 1100 (−20)
</pre>
</div>
As for addition, overflow in subtraction may be avoided (or detected after the operation) by first sign-extending both inputs by an extra bit.
Line 482 ⟶ 508:
|archive-url = https://web.archive.org/web/20150213203512/http://pages.cs.wisc.edu/~cs354-1/beyond354/int.mult.html
|archive-date = February 13, 2015
}}</ref> For example, take {{math|1=6
<div style="overflow-x: auto;">
<pre style="width:25em">
00000110 (6)
Line 498 ⟶ 526:
xx11100010
</pre>
</div>
This is very inefficient; by doubling the precision ahead of time, all additions must be double-precision and at least twice as many partial products are needed than for the more efficient algorithms actually implemented in computers. Some multiplication algorithms are designed for two's complement, notably [[Booth's multiplication algorithm]]. Methods for multiplying sign-magnitude numbers do not work with two's-complement numbers without adaptation. There is not usually a problem when the multiplicand (the one being repeatedly added to form the product) is negative; the issue is setting the initial bits of the product correctly when the multiplier is negative. Two methods for adapting algorithms to handle two's-complement numbers are common:
* First check to see if the multiplier is negative. If so, negate (
* Subtract the partial product resulting from the MSB (pseudo sign bit) instead of adding it like the other partial products. This method requires the multiplicand's sign bit to be extended by one position, being preserved during the shift right actions.<ref>{{cite book |first=John F. |last=Wakerly |title=Digital Design Principles & Practices |publisher=Prentice Hall |edition=3rd |year=2000 |page=47 |isbn=0-13-769191-2 }}</ref>
As an example of the second method, take the common add-and-shift algorithm for multiplication. Instead of shifting partial products to the left as is done with pencil and paper, the accumulated product is shifted right, into a second register that will eventually hold the least significant half of the product. Since the [[least significant bit]]s are not changed once they are calculated, the additions can be single precision, accumulating in the register that will eventually hold the most significant half of the product. In the following example, again multiplying 6 by
<pre style="width:90%;overflow:scroll;white-space:pre">
0 0110 (6) (multiplicand with extended sign bit)
Line 522 ⟶ 552:
[[Comparison (computer programming)|Comparison]] is often implemented with a dummy subtraction, where the flags in the computer's [[status register]] are checked, but the main result is ignored. The [[zero flag]] indicates if two values compared equal. If the exclusive-or of the [[Sign flag|sign]] and [[Overflow flag|overflow]] flags is 1, the subtraction result was less than zero, otherwise the result was zero or greater. These checks are often implemented in computers in [[conditional branch]] instructions.
Unsigned binary numbers can be ordered by a simple [[lexicographic ordering]], where the bit value 0 is defined as less than the bit value 1.
The following algorithm (for an {{mvar|n}}-bit two's complement architecture) sets the result register R to −1 if A < B, to +1 if A > B, and to 0 if A and B are equal:
Line 529 ⟶ 559:
// reversed comparison of the sign bit
if A(n-1)
return +1;
else if A(n-1)
return -1
end;
// comparison of remaining bits
for i := n-2
if A(i)
return -1
else if A(i)
return +1
end
Line 548 ⟶ 578:
</syntaxhighlight>
==Two's complement and {{nowrap|2-adic}} numbers==
In a classic ''[[HAKMEM]]'' published by the [[MIT AI Lab]] in 1972, [[Bill Gosper]] noted that whether or not a machine's internal representation was two's-complement could be determined by summing the successive powers of two. In a flight of fancy, he noted that the result of doing this algebraically indicated that "algebra is run on a machine (the universe) which is two's-complement."<ref>{{cite web |url=http://www.inwap.com/pdp10/hbaker/hakmem/hacks.html#item154 |title=Programming Hacks |work=HAKMEM |at=ITEM 154 (Gosper) |archive-url=https://web.archive.org/web/20240224184437/http://www.inwap.com/pdp10/hbaker/hakmem/hacks.html#item154 |archive-date=2024-02-24 |url-status=dead}}</ref>
Gosper's end conclusion is not necessarily meant to be taken seriously, and it is akin to a [[mathematical joke]]. The critical step is "...110 = ...111 − 1", i.e., "2''X'' = ''X'' − 1", and thus ''X'' = ...111 = −1. This presupposes a method by which an infinite string of 1s is considered a number, which requires an extension of the finite place-value concepts in elementary arithmetic.<!--Does this interpretation take into account a sign bit?--> It is meaningful either as part of a two's-complement notation for all integers, as a typical [[p-adic number|2-adic number]], or even as one of the generalized sums defined for the [[divergent series]] of real numbers [[1 + 2 + 4 + 8 +
== Fraction conversion ==
Line 573 ⟶ 603:
==Further reading==
* [https://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html Two's Complement Explanation
*{{cite book |first=Israel |last=Koren |title=Computer Arithmetic Algorithms |publisher=A. K. Peters |year=2002 |isbn=1-56881-160-8 }}
*{{cite book |first=Ivan |last=Flores |title=The Logic of Computer Arithmetic |publisher=Prentice-Hall |year=1963 }}
|