Content deleted Content added
m Made it clearer Tags: Visual edit Mobile edit Mobile web edit |
Hairy Dude (talk | contribs) minus signs (replace incorrectly used en dashes); display="block"; replace invalid style attributes with CSS; {{hatnote}}; rm inappropriate italics; make example code valid Pascal (as highlighted); consistently use spaced en dashes Tags: Mobile edit Mobile web edit Advanced mobile edit |
||
Line 1:
{{Short description|Mathematical operation on binary numbers, and a number representation based on this operation}}
'''Two's complement''' is the most common [[signed number representations|method of representing signed]] (positive, negative, and zero) [[Integer (computer science)|integers]] on computers,<ref>E.g. "Signed integers are two's complement binary values that can be used to represent both positive and negative integer values
Unlike the [[ones' complement]] scheme, the two's complement scheme has only one representation for zero. Furthermore, arithmetic implementations can be used on signed as well as unsigned integers<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 61:
==Theory==
Two's complement is an example of a [[Method of complements|radix complement]].
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"
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:
| −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:
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 ⟶ 176:
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, so the value represented is negative.
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:
Likewise, the two's complement of zero is zero: inverting gives all ones, and adding one changes the ones back to zeros (since the overflow is ignored).
Line 194 ⟶ 196:
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 ⟶ 210:
{{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 ⟶ 217:
!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 ⟶ 231:
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 ⟶ 256:
|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 ⟶ 263:
|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 ⟶ 281:
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 ⟶ 309:
==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 ⟶ 328:
!Binary (8-bit)
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|-
|
|}
===Example===
For example, an 8 bit number can only represent every integer from
<pre style="width:25em">
1111 1111 255.
Line 361 ⟶ 363:
1010 0001 (two's complement) 161.
</pre>
{|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=http://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html |access-date=2014-06-22
}}</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 ⟶ 417:
===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">
0000 1111 (15)
Line 434 ⟶ 436:
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.
<pre style="width:25em">
0111 (carry)
Line 444 ⟶ 446:
1010 (−6) invalid!
</pre>
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
===Subtraction===
Line 482 ⟶ 484:
|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
<pre style="width:25em">
00000110 (6)
Line 500 ⟶ 502:
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 ⟶ 524:
[[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 ⟶ 531:
// 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 551 ⟶ 553:
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 ⟶ 575:
==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 }}
|