Two's complement is a
mathematical operation
In mathematics, an operation is a Function (mathematics), function which takes zero or more input values (also called "''operands''" or "arguments") to a well-defined output value. The number of operands is the arity of the operation.
The most c ...
to reversibly convert a positive
binary number
A binary number is a number expressed in the base-2 numeral system or binary numeral system, a method of mathematical expression which uses only two symbols: typically "0" (zero) and "1" ( one).
The base-2 numeral system is a positional notatio ...
into a negative binary number with equivalent (but negative) value, using the
binary digit with the greatest place value (the leftmost bit in big-
endian numbers, rightmost bit in little-endian numbers) to indicate whether the binary number is positive or negative (the sign). It is used in
computer science
Computer science is the study of computation, automation, and information. Computer science spans theoretical disciplines (such as algorithms, theory of computation, information theory, and automation) to Applied science, practical discipli ...
as the most common
method of representing signed (positive, negative, and zero)
integers
An integer is the number zero (), a positive natural number (, , , etc.) or a negative integer with a minus sign (−1, −2, −3, etc.). The negative numbers are the additive inverses of the corresponding positive numbers. In the language o ...
on computers, and more generally,
fixed point binary values. When the
most significant bit
In computing, bit numbering is the convention used to identify the bit positions in a binary number.
Bit significance and indexing
In computing, the least significant bit (LSB) is the bit position in a binary integer representing the binary 1 ...
is a one, the number is signed as negative. .
Two's complement is executed by
1) inverting (i.e. flipping) all bits, then
2) adding a place value of 1 to the inverted number. For example, say the number −6 is of interest. +6 in binary is 0110 (the leftmost most significant bit is needed for the sign; positive 6 is not 110 because it would be interpreted as -2). Step one is to flip all bits, yielding 1001. Step two is to add the place value one to the flipped number, which yields 1010. To verify that 1010 indeed has a value of −6, remember that two's complement makes the most significant bit represent a negative place value, then add the place values: 1010 = -1×(2
3)+0×(2
2)+1×(2
1)+0×(2
0) = -1(8) + 0 + 1(2) + 0 = −6.
Theory
Two's complement is an example of a
radix complement
In mathematics and computing, the method of complements is a technique to encode a symmetric range of positive and negative integers in a way that they can use the same algorithm (hardware) for addition throughout the whole range. For a given num ...
.
The 'two' in the name refers to the term which, expanded fully in an -bit system, is actually "two to the power of N" - (the only case where exactly 'two' would be produced in this term is , so for a 1-bit system, but these don't have capacity for both a sign and a zero), and it is only this full term in respect to which the
complement
A complement is something that completes something else.
Complement may refer specifically to:
The arts
* Complement (music), an interval that, when added to another, spans an octave
** Aggregate complementation, the separation of pitch-class ...
is calculated. As such, the precise definition of the ''Two's complement'' of an -bit number is the
complement
A complement is something that completes something else.
Complement may refer specifically to:
The arts
* Complement (music), an interval that, when added to another, spans an octave
** Aggregate complementation, the separation of pitch-class ...
of that number with respect to .
The defining property of being a ''complement to a number with respect to '' is simply that the summation of this number with the original produce . For example, using binary with numbers up to three-bits (so and , where '
2' indicates a binary representation), a two's complement for the number 3 () is 5 (), because summed to the original it gives . Where this correspondence is employed for representing negative numbers, it effectively means, using an analogy with decimal digits and a number-space only allowing eight non-negative numbers 0 through 7, dividing the number-space in two sets: the first four of the numbers 0 1 2 3 remain the same, while the remaining four encode negative numbers, maintaining their growing order, so making 4 encode -4, 5 encode -3, 6 encode -2 and 7 encode -1. A binary representation has an additional utility however, because the most significant bit also indicates the group (and the sign): it is 0 for the first group of non-negatives, and 1 for the second group of negatives. The tables at right illustrate this property.
Calculation of the binary two's complement of a positive number essentially means subtracting the number from the . But as can be seen for the three-bit example and the four-bit (), the number will not itself be representable in a system limited to bits, as it is just outside the bits space (the number is nevertheless the reference point of the "Two's complement" in an -bit system). Because of this, systems with maximally -bits must break the subtraction into two operations: first subtract from the maximum number in the -bit system, that is (this term in binary is actually a simple number consisting of 'all 1s', and a subtraction from it can be done simply by inverting all bits in the number also known as
the bitwise NOT operation) and then adding the one. Coincidentally, that intermediate number before adding the one is also used in computer science as another method of signed number representation and is called a
Ones' complement
The ones' complement of a binary number is the value obtained by inverting all the bits in the binary representation of the number (swapping 0s and 1s). The name "ones' complement" (''note this is possessive of the plural "ones", not of a sing ...
(named that because summing such a number with the original gives the 'all 1s').
Compared to other systems for representing signed numbers (''e.g.,''
ones' complement
The ones' complement of a binary number is the value obtained by inverting all the bits in the binary representation of the number (swapping 0s and 1s). The name "ones' complement" (''note this is possessive of the plural "ones", not of a sing ...
), the two's complement has the advantage that the fundamental arithmetic operations of
addition
Addition (usually signified by the Plus and minus signs#Plus sign, plus symbol ) is one of the four basic Operation (mathematics), operations of arithmetic, the other three being subtraction, multiplication and Division (mathematics), division. ...
,
subtraction
Subtraction is an arithmetic operation that represents the operation of removing objects from a collection. Subtraction is signified by the minus sign, . For example, in the adjacent picture, there are peaches—meaning 5 peaches with 2 taken ...
, and
multiplication
Multiplication (often denoted by the cross symbol , by the mid-line dot operator , by juxtaposition, or, on computers, by an asterisk ) is one of the four elementary mathematical operations of arithmetic, with the other ones being additi ...
are identical to those for unsigned binary numbers (as long as the inputs are represented in the same number of bits as the output, and any
overflow beyond those bits is discarded from the result). This property makes the system simpler to implement, especially for higher-precision arithmetic. Additionally, unlike ones' complement systems, two's complement has no representation for
negative zero
Signed zero is zero with an associated sign. In ordinary arithmetic, the number 0 does not have a sign, so that −0, +0 and 0 are identical. However, in computing, some number representations allow for the existence of two zeros, often denoted by ...
, and thus does not suffer from its associated difficulties. Otherwise, both schemes have the desired property that the sign of integers can be reversed by taking the complement of its binary representation, but Two's component has an exception - the lowest negative, as can be seen in the tables.
History
The
method of complements
In mathematics and computing, the method of complements is a technique to encode a symmetric range of positive and negative integers in a way that they can use the same algorithm (hardware) for addition throughout the whole range. For a given num ...
had long been used to perform subtraction in decimal
adding machine
An adding machine is a class of mechanical calculator, usually specialized for bookkeeping calculations.
In the United States, the earliest adding machines were usually built to read in dollars and cents. Adding machines were ubiquitous off ...
s and
mechanical calculator
A mechanical calculator, or calculating machine, is a mechanical device used to perform the basic operations of arithmetic automatically, or (historically) a simulation such as an analog computer or a slide rule. Most mechanical calculators wer ...
s.
John von Neumann
John von Neumann (; hu, Neumann János Lajos, ; December 28, 1903 – February 8, 1957) was a Hungarian-American mathematician, physicist, computer scientist, engineer and polymath. He was regarded as having perhaps the widest cove ...
suggested use of two's complement binary representation in his 1945 ''
First Draft of a Report on the EDVAC
The ''First Draft of a Report on the EDVAC'' (commonly shortened to ''First Draft'') is an incomplete 101-page document written by John von Neumann and distributed on June 30, 1945 by Herman Goldstine, security officer on the classified ENIAC pro ...
'' proposal for an electronic stored-program digital computer.
The 1949
EDSAC
The Electronic Delay Storage Automatic Calculator (EDSAC) was an early British computer. Inspired by John von Neumann's seminal ''First Draft of a Report on the EDVAC'', the machine was constructed by Maurice Wilkes and his team at the Universi ...
, which was inspired by the ''First Draft'', used two's complement representation of negative binary integers.
Many early computers, including the
CDC 6600
The CDC 6600 was the flagship of the 6000 series of mainframe computer systems manufactured by Control Data Corporation. Generally considered to be the first successful supercomputer, it outperformed the industry's prior recordholder, the IBM ...
, the
LINC
The LINC (Laboratory INstrument Computer) is a 12-bit, 2048-word transistorized computer. The LINC is considered by some the first minicomputer and a forerunner to the personal computer. Originally named the "Linc", suggesting the project's o ...
, the
PDP-1
The PDP-1 (''Programmed Data Processor-1'') is the first computer in Digital Equipment Corporation's PDP series and was first produced in 1959. It is famous for being the computer most important in the creation of hacker culture at Massachusetts ...
, and the UNIVAC 1107, use
ones' complement
The ones' complement of a binary number is the value obtained by inverting all the bits in the binary representation of the number (swapping 0s and 1s). The name "ones' complement" (''note this is possessive of the plural "ones", not of a sing ...
notation; the descendants of the UNIVAC 1107, the
UNIVAC 1100/2200 series
The UNIVAC 1100/2200 series is a series of compatible 36-bit computer systems, beginning with the UNIVAC 1107 in 1962, initially made by Sperry Rand. The series continues to be supported today by Unisys Corporation as the ClearPath Dorado Series. ...
, continued to do so. The
IBM 700/7000 series
The IBM 700/7000 series is a series of large-scale (Mainframe computer, mainframe) computer systems that were made by IBM through the 1950s and early 1960s. The series includes several different, incompatible processor architectures. The 700s ...
scientific machines use sign/magnitude notation, except for the index registers which are two's complement. Early commercial computers storing negative values in two's complement form include the
English Electric DEUCE
The DEUCE (''Digital Electronic Universal Computing Engine'') was one of the earliest United Kingdom, British commercially available computers, built by English Electric from 1955. It was the production version of the Pilot ACE, itself a cut-do ...
(1955),
Digital Equipment Corporation
Digital Equipment Corporation (DEC ), using the trademark Digital, was a major American company in the computer industry from the 1960s to the 1990s. The company was co-founded by Ken Olsen and Harlan Anderson in 1957. Olsen was president unt ...
PDP-5
The PDP-5 was Digital Equipment Corporation's first 12-bit computer, introduced in 1963.
History
An earlier 12-bit computer, named LINC has been described as the first minicomputer and also "the first modern personal computer." It had 2,048 12 ...
and the 1963
PDP-6
The PDP-6, short for Programmed Data Processor model 6, is a computer developed by Digital Equipment Corporation (DEC) during 1963 and first delivered in the summer of 1964.
It was an expansion of DEC's existing 18-bit systems to use a 36-bit da ...
. The
System/360
The IBM System/360 (S/360) is a family of mainframe computer systems that was announced by IBM on April 7, 1964, and delivered between 1965 and 1978. It was the first family of computers designed to cover both commercial and scientific applica ...
, introduced in 1964 by
IBM, then the dominant player in the computer industry, made two's complement the most widely used binary representation in the computer industry. The first minicomputer, the
PDP-8
The PDP-8 is a 12-bit computing, 12-bit minicomputer that was produced by Digital Equipment Corporation, Digital Equipment Corporation (DEC). It was the first commercially successful minicomputer, with over 50,000 units being sold over the model's ...
introduced in 1965, uses two's complement arithmetic as do the 1969
Data General Nova
The Data General Nova is a series of 16-bit minicomputers released by the American company Data General. The Nova family was very popular in the 1970s and ultimately sold tens of thousands of units.
The first model, known simply as "Nova", was ...
, the 1970
PDP-11
The PDP-11 is a series of 16-bit minicomputers sold by Digital Equipment Corporation (DEC) from 1970 into the 1990s, one of a set of products in the Programmed Data Processor (PDP) series. In total, around 600,000 PDP-11s of all models were sold, ...
, and almost all subsequent minicomputers and microcomputers.
Converting from two's complement representation
A two's-complement number system encodes positive and negative numbers in a binary number representation. The weight of each bit is a power of two, except for the
most significant bit
In computing, bit numbering is the convention used to identify the bit positions in a binary number.
Bit significance and indexing
In computing, the least significant bit (LSB) is the bit position in a binary integer representing the binary 1 ...
, whose weight is the negative of the corresponding power of two.
The value of an -bit integer
is given by the following formula:
:
The most significant bit determines the sign of the number and is sometimes called the
sign bit
In computer science, the sign bit is a bit in a signed number representation that indicates the sign of a number. Although only signed numeric data types have a sign bit, it is invariably located in the most significant bit position, so the term ...
. Unlike in
sign-and-magnitude
In computing, signed number representations are required to encode negative numbers in binary number systems.
In mathematics, negative numbers in any base are represented by prefixing them with a minus sign ("−"). However, in RAM or CPU regist ...
representation, the sign bit also has the weight shown above. Using bits, all integers from to can be represented.
Converting to two's complement representation
In two's complement notation, a ''non-negative'' number is represented by its ordinary
binary representation
A binary number is a number expressed in the base-2 numeral system or binary numeral system, a method of mathematical expression which uses only two symbols: typically "0" (zero) and "1" (one).
The base-2 numeral system is a positional notation ...
; in this case, the most significant bit is 0. Though, the range of numbers represented is not the same as with unsigned binary numbers. For example, an 8-bit unsigned number can represent the values 0 to 255 (11111111). However a two's complement 8-bit number can only represent positive integers from 0 to 127 (01111111), because the rest of the bit combinations with the most significant bit as '1' represent the negative integers −1 to −128.
The two's complement operation is the
additive inverse
In mathematics, the additive inverse of a number is the number that, when added to , yields zero. This number is also known as the opposite (number), sign change, and negation. For a real number, it reverses its sign: the additive inverse (opp ...
operation, so negative numbers are represented by the two's complement of the
absolute value
In mathematics, the absolute value or modulus of a real number x, is the non-negative value without regard to its sign. Namely, , x, =x if is a positive number, and , x, =-x if x is negative (in which case negating x makes -x positive), an ...
.
From the ones' complement
To get the two's complement of a negative binary number, all
bit
The bit is the most basic unit of information in computing and digital communications. The name is a portmanteau of binary digit. The bit represents a logical state with one of two possible values. These values are most commonly represente ...
s are inverted, or "flipped", by using the
bitwise NOT
In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral (considered as a bit string) at the level of its individual bits. It is a fast and simple action, basic to the higher-level arithmetic operati ...
operation; the value of 1 is then added to the resulting value, ignoring the overflow which occurs when taking the two's complement of 0.
For example, using 1 byte (=8 bits), the decimal number 5 is represented by
:0000 0101
2
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:
:1111 1010
2
At this point, the representation is the
ones' complement
The ones' complement of a binary number is the value obtained by inverting all the bits in the binary representation of the number (swapping 0s and 1s). The name "ones' complement" (''note this is possessive of the plural "ones", not of a sing ...
of the decimal value −5. To obtain the two's complement, 1 is added to the result, giving:
:1111 1011
2
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:
:0000 0100
2
And adding one gives the final value:
:0000 0101
2
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).
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 below.
Subtraction from 2''N''
The sum of a number and its ones' complement is an -bit word with all 1 bits, which is (reading as an unsigned binary number) . Then adding a number to its two's complement results in the lowest bits set to 0 and the carry bit 1, where the latter has the weight (reading it as an unsigned binary number) of . Hence, in the unsigned binary arithmetic the value of two's-complement negative number of a positive satisfies the equality .
For example, to find the four-bit representation of −5 (subscripts denote the
base of the representation):
: therefore
Hence, with :
:
The calculation can be done entirely in base 10, converting to base 2 at the end:
:
Working from LSB towards MSB
A shortcut to manually convert a
binary number
A binary number is a number expressed in the base-2 numeral system or binary numeral system, a method of mathematical expression which uses only two symbols: typically "0" (zero) and "1" ( one).
The base-2 numeral system is a positional notatio ...
into its two's complement is to start at the
least significant bit
In computing, bit numbering is the convention used to identify the bit positions in a binary number.
Bit significance and indexing
In computing, the least significant bit (LSB) is the bit position in a binary integer representing the binary 1 ...
(LSB), and copy all the zeros, working from LSB toward the most significant bit (MSB) until the first 1 is reached; then copy that 1, and flip all the remaining bits (Leave the MSB as a 1 if the initial number was in sign-and-magnitude representation). This shortcut allows a person to convert a number to its two's complement without first forming its ones' complement. For example: in two's complement representation, the negation of "0011 1100" is "1100 0
100", where the underlined digits were unchanged by the copying operation (while the rest of the digits were flipped).
In computer circuitry, this method is no faster than the "complement and add one" method; both methods require working sequentially from right to left, propagating logic changes. The method of complementing and adding one can be sped up by a standard
carry look-ahead adder
A carry-lookahead adder (CLA) or fast adder is a type of electronics adder used in digital logic. A carry-lookahead adder improves speed by reducing the amount of time required to determine carry bits. It can be contrasted with the simpler, b ...
circuit; the LSB towards MSB method can be sped up by a similar logic transformation.
Sign extension
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. Some processors do this in a single instruction; on other processors, a conditional must be used followed by code to set the relevant bits or bytes.
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. However, if the most-significant bit changes from 0 to 1 (and vice versa), overflow is said to occur in the case that the value represents a signed integer.
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.
Most negative number
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.
Taking the two's complement of the minimum number in the range will not have the desired effect of negating the number. For example, the two's complement of −128 in an eight-bit system is −128. Although the expected result from negating −128 is +128, there is no representation of +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.
Mathematically, this is complementary to the fact that the negative of 0 is again 0. For a given number of bits there is an even number of binary numbers 2
, taking negatives is a
group action
In mathematics, a group action on a space is a group homomorphism of a given group into the group of transformations of the space. Similarly, a group action on a mathematical structure is a group homomorphism of a group into the automorphism ...
(of the group of order 2) on binary numbers, and since the
orbit
In celestial mechanics, an orbit is the curved trajectory of an object such as the trajectory of a planet around a star, or of a natural satellite around a planet, or of an artificial satellite around an object or position in space such as a p ...
of zero has order 1, at least one other number must have an orbit of order 1 for the orders of the orbits to add up to the order of the set. Thus some other number must be invariant under taking negatives (formally, by the
orbit-stabilizer theorem
In mathematics, a group action on a space is a group homomorphism of a given group into the group of transformations of the space. Similarly, a group action on a mathematical structure is a group homomorphism of a group into the automorphism ...
). Geometrically, one can view the -bit binary numbers as the
cyclic group
In group theory, a branch of abstract algebra in pure mathematics, a cyclic group or monogenous group is a group, denoted C''n'', that is generated by a single element. That is, it is a set of invertible elements with a single associative bina ...
, which can be visualized as a circle (or properly a regular 2
-gon), and taking negatives is a reflection, which fixes the elements of order dividing 2: 0 and the opposite point, or visually the zenith and nadir.
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., −(−128) → −128.
* an implementation of
absolute value
In mathematics, the absolute value or modulus of a real number x, is the non-negative value without regard to its sign. Namely, , x, =x if is a positive number, and , x, =-x if x is negative (in which case negating x makes -x positive), an ...
may return a negative number. e.g., abs(−128) → −128.
* Likewise, multiplication by −1 may fail to function as expected. e.g., (−128) × (−1) → −128.
* Division by −1 may cause an exception (like that caused by dividing by 0). Even calculating the remainder (or modulo) by −1 can trigger this exception.
e.g., (−128) ÷ (−1) → crash, (−128) % (−1) → crash.
In the
C and
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
programming languages, the above behaviours are
undefined
Undefined may refer to:
Mathematics
* Undefined (mathematics), with several related meanings
** Indeterminate form, in calculus
Computing
* Undefined behavior, computer code whose behavior is not specified under certain conditions
* Undefined v ...
and not only may they return strange results, but the compiler is free to assume that the programmer has ensured that undefined computations never happen, and make inferences from that assumption.
This enables a number of optimizations, but also leads to a number of strange bugs in such undefined programs.
The most negative number in two's complement is sometimes called "the weird number", because it is the only exception. Although the number is an exception, it is a valid number in regular two's complement systems. All arithmetic operations work with it both as an operand and (unless there was an overflow) a result.
Why it works
Given a set of all possible -bit values, we can assign the lower (by the binary value) half to be the integers from 0 to inclusive and the upper half to be to −1 inclusive. The upper half (again, by the binary value) can be used to represent negative integers from to −1 because, under addition modulo they behave the same way as those negative integers. That is to say that because any value in the set can be used in place of .
For example, with eight bits, the unsigned bytes are 0 to 255. Subtracting 256 from the top half (128 to 255) yields the signed bytes −128 to −1.
The relationship to two's complement is realised by noting that , and is the
ones' complement
The ones' complement of a binary number is the value obtained by inverting all the bits in the binary representation of the number (swapping 0s and 1s). The name "ones' complement" (''note this is possessive of the plural "ones", not of a sing ...
of .
Example
:''In this subsection, decimal numbers are suffixed with a decimal point "."''
For example, an 8 bit number can only represent every integer from −128. to 127., inclusive, since . is equivalent to 161. since
:−95. + 256.
:= −95. + 255. + 1
:= 255. − 95. + 1
:= 160. + 1.
:= 161.
1111 1111 255.
− 0101 1111 − 95.
=
1010 0000 (ones' complement) 160.
+ 1 + 1
=
1010 0001 (two's complement) 161.
Fundamentally, the system represents negative integers by counting backward and
wrapping around. The boundary between positive and negative numbers is arbitrary, but by
convention all negative numbers have a left-most bit (
most significant bit
In computing, bit numbering is the convention used to identify the bit positions in a binary number.
Bit significance and indexing
In computing, the least significant bit (LSB) is the bit position in a binary integer representing the binary 1 ...
) of one. Therefore, the most positive four-bit number is 0111 (7.) and the most negative is 1000 (−8.). Because of the use of the left-most bit as the sign bit, the absolute value of the most negative number (, −8., = 8.) is too large to represent. Negating a two's complement number is simple: Invert all the bits and add one to the result. For example, negating 1111, we get . Therefore, 1111 in binary must represent −1 in decimal.
The system is useful in simplifying the implementation of arithmetic on computer hardware. Adding 0011 (3.) to 1111 (−1.) at first seems to give the incorrect answer of 10010. However, the hardware can simply ignore the left-most bit to give the correct answer of 0010 (2.). Overflow checks still must exist to catch operations such as summing 0100 and 0100.
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.
Arithmetic operations
Addition
Adding twos-complement numbers requires no special processing even if the operands have opposite signs: the sign of the result is determined automatically. For example, adding 15 and −5:
0000 1111 (15)
+ 1111 1011 (−5)
0000 1010 (10)
Or the computation of 5 − 15 = 5 + (−15):
0000 0101 ( 5)
+ 1111 0001 (−15)
1111 0110 (−10)
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
10.
The last two bits of the
carry
Carry or carrying may refer to:
People
*Carry (name)
Finance
* Carried interest (or carry), the share of profits in an investment fund paid to the fund manager
* Carry (investment), a financial term: the carry of an asset is the gain or cost of h ...
row (reading right-to-left) contain vital information: whether the calculation resulted in an
arithmetic overflow
Arithmetic () is an elementary part of mathematics that consists of the study of the properties of the traditional operations on numbers—addition, subtraction, multiplication, division, exponentiation, and extraction of roots. In the 19th cen ...
, a number too large for the binary system to represent (in this case greater than 8 bits). An overflow condition exists when these last two bits are different from one another. As mentioned above, the sign of the number is encoded in the MSB of the result.
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. Conveniently, an
XOR
Exclusive or or exclusive disjunction is a logical operation that is true if and only if its arguments differ (one is true, the other is false).
It is symbolized by the prefix operator J and by the infix operators XOR ( or ), EOR, EXOR, , ...
operation on these two bits can quickly determine if an overflow condition exists. As an example, consider the signed 4-bit addition of 7 and 3:
0111 (carry)
0111 (7)
+ 0011 (3)
1010 (−6) invalid!
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
2 = 10
10 is outside the permitted range of −8 to 7. The result would be correct if treated as unsigned integer.
In general, any two -bit numbers may be added ''without'' overflow, by first sign-extending both of them to bits, and then adding as above. The bits result is large enough to represent any possible sum ( 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 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.
Subtraction
Computers usually use the
method of complements
In mathematics and computing, the method of complements is a technique to encode a symmetric range of positive and negative integers in a way that they can use the same algorithm (hardware) for addition throughout the whole range. For a given num ...
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:
11110 000 (borrow)
0000 1111 (15)
− 1111 1011 (−5)
0001 0100 (20)
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:
11100 000 (borrow)
0000 1111 (15)
− 0010 0011 (35)
1110 1100 (−20)
As for addition, overflow in subtraction may be avoided (or detected after the operation) by first sign-extending both inputs by an extra bit.
Multiplication
The product of two -bit numbers requires bits to contain all possible values.
If the precision of the two operands using two's complement is doubled before the multiplication, direct multiplication (discarding any excess bits beyond that precision) will provide the correct result. For example, take . First, the precision is extended from four bits to eight. Then the numbers are multiplied, discarding the bits beyond the eighth bit (as shown by ""):
00000110 (6)
* 11111011 (−5)
110
1100
00000
110000
1100000
11000000
x10000000
+ xx00000000
xx11100010
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
Booth's multiplication algorithm is a multiplication algorithm that multiplies two signed binary numbers in two's complement notation. The algorithm was invented by Andrew Donald Booth in 1950 while doing research on crystallography at Birkbeck Co ...
. Methods for multiplying sign-magnitude numbers don't work with two's-complement numbers without adaptation. There isn't 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 (''i.e.'', take the two's complement of) both operands before multiplying. The multiplier will then be positive so the algorithm will work. Because both operands are negated, the result will still have the correct sign.
* 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.
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
In computing, bit numbering is the convention used to identify the bit positions in a binary number.
Bit significance and indexing
In computing, the least significant bit (LSB) is the bit position in a binary integer representing the binary 1 ...
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 −5, the two registers and the extended sign bit are separated by ", ":
0 0110 (6) (multiplicand with extended sign bit)
× 1011 (−5) (multiplier)
=, ,
0, 0110, 0000 (first partial product (rightmost bit is 1))
0, 0011, 0000 (shift right, preserving extended sign bit)
0, 1001, 0000 (add second partial product (next bit is 1))
0, 0100, 1000 (shift right, preserving extended sign bit)
0, 0100, 1000 (add third partial product: 0 so no change)
0, 0010, 0100 (shift right, preserving extended sign bit)
1, 1100, 0100 (subtract last partial product since it's from sign bit)
1, 1110, 0010 (shift right, preserving extended sign bit)
, 1110, 0010 (discard extended sign bit, giving the final answer, −30)
Comparison (ordering)
Comparison
Comparison or comparing is the act of evaluating two or more things by determining the relevant, comparable characteristics of each thing, and then determining which characteristics of each are similar to the other, which are different, and t ...
is often implemented with a dummy subtraction, where the flags in the computer's
status register
A status register, flag register, or condition code register (CCR) is a collection of status Flag (computing), flag bits for a Central processing unit, processor. Examples of such registers include FLAGS register (computing), FLAGS register in the ...
are checked, but the main result is ignored. The
zero flag
The zero flag is a single bit flag that is a central feature on most conventional CPU architectures (including x86, ARM, PDP-11, 68000, 6502, and numerous others). It is often stored in a dedicated register, typically called status register or f ...
indicates if two values compared equal. If the exclusive-or of the
sign
A sign is an object, quality, event, or entity whose presence or occurrence indicates the probable presence or occurrence of something else. A natural sign bears a causal relation to its object—for instance, thunder is a sign of storm, or me ...
and
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
A branch is an instruction in a computer program that can cause a computer to begin executing a different instruction sequence and thus deviate from its default behavior of executing instructions in order. ''Branch'' (or ''branching'', ''branc ...
instructions.
Unsigned binary numbers can be ordered by a simple
lexicographic ordering
In mathematics, the lexicographic or lexicographical order (also known as lexical order, or dictionary order) is a generalization of the alphabetical order of the dictionaries to sequences of ordered symbols or, more generally, of elements of ...
, where the bit value 0 is defined as less than the bit value 1. For two's complement values, the meaning of the most significant bit is reversed (i.e. 1 is less than 0).
The following algorithm (for an -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:
// reversed comparison of the sign bit
if A(n-1) 0 and B(n-1) 1 then
return +1
else if A(n-1) 1 and B(n-1) 0 then
return -1
end
// comparison of remaining bits
for i = n-2...0 do
if A(i) 0 and B(i) 1 then
return -1
else if A(i) 1 and B(i) 0 then
return +1
end
end
return 0
Two's complement and 2-adic numbers
In a classic ''
HAKMEM
HAKMEM, alternatively known as AI Memo 239, is a February 1972 "memo" (technical report) of the MIT AI Lab containing a wide variety of hacks, including useful and clever algorithms for mathematical computation, some number theory and schematic ...
'' published by the
MIT AI Lab
Computer Science and Artificial Intelligence Laboratory (CSAIL) is a research institute at the Massachusetts Institute of Technology (MIT) formed by the 2003 merger of the Laboratory for Computer Science (LCS) and the Artificial Intelligence La ...
in 1972,
Bill Gosper
Ralph William Gosper Jr. (born April 26, 1943), known as Bill Gosper, is an American mathematician and programmer. Along with Richard Greenblatt, he may be considered to have founded the hacker community, and he holds a place of pride in the L ...
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."
Gosper's end conclusion is not necessarily meant to be taken seriously, and it is akin to a
mathematical joke
A mathematical joke is a form of humor which relies on aspects of mathematics or a stereotype of mathematicians. The humor may come from a pun, or from a double meaning of a mathematical term, or from a lay person's misunderstanding of a mathemati ...
. 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. It is meaningful either as part of a two's-complement notation for all integers, as a typical
2-adic number, or even as one of the generalized sums defined for the
divergent series
In mathematics, a divergent series is an infinite series that is not convergent, meaning that the infinite sequence of the partial sums of the series does not have a finite limit.
If a series converges, the individual terms of the series must ...
of real numbers
1 + 2 + 4 + 8 + ···. Digital arithmetic circuits, idealized to operate with infinite (extending to positive powers of 2) bit strings, produce 2-adic addition and multiplication compatible with two's complement representation.
Continuity of binary arithmetical and
bitwise operation
In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral (considered as a bit string) at the level of its individual bits. It is a fast and simple action, basic to the higher-level arithmetic operati ...
s in 2-adic
metric
Metric or metrical may refer to:
* Metric system, an internationally adopted decimal system of measurement
* An adjective indicating relation to measurement in general, or a noun describing a specific type of measurement
Mathematics
In mathema ...
also has some use in cryptography.
Fraction conversion
To convert a number with a fractional part, such as .0101, one must convert starting from right to left the 1s to decimal as in a normal conversion. In this example 0101 is equal to 5 in decimal. Each digit after the floating point represents a fraction where the denominator is a multiplier of 2. So, the first is 1/2, the second is 1/4 and so on. Having already calculated the decimal value as mentioned above, only the denominator of the LSB (LSB = starting from right) is used. The final result of this conversion is 5/16.
For instance, having the floating value of .0110 for this method to work, one should not consider the last 0 from the right. Hence, instead of calculating the decimal value for 0110, we calculate the value 011, which is 3 in decimal (by leaving the 0 in the end, the result would have been 6, together with the denominator 2
4 = 16, which reduces to 3/8). The denominator is 8, giving a final result if 3/8.
See also
*
Division algorithm
A division algorithm is an algorithm which, given two integers N and D, computes their quotient and/or remainder, the result of Euclidean division. Some are applied by hand, while others are employed by digital circuit designs and software.
Divis ...
, including restoring and non-restoring division in two's-complement representations
*
Offset binary
Offset binary, also referred to as excess-K, excess-''N'', excess-e, excess code or biased representation, is a method for signed number representation where a signed number n is represented by the bit pattern corresponding to the unsigned numbe ...
*
p-adic number
In mathematics, the -adic number system for any prime number extends the ordinary arithmetic of the rational numbers in a different way from the extension of the rational number system to the real and complex number systems. The extensi ...
*
Method of complements
In mathematics and computing, the method of complements is a technique to encode a symmetric range of positive and negative integers in a way that they can use the same algorithm (hardware) for addition throughout the whole range. For a given num ...
, generalisation to other number bases, used on mechanical calculators
References
Further reading
Two's Complement Explanation, (Thomas Finley, 2000)
*
*{{cite book , first=Ivan , last=Flores , title=The Logic of Computer Arithmetic , publisher=Prentice-Hall , year=1963
External links
Two's complement array multiplier JavaScript simulator
Binary arithmetic
Articles with example Python (programming language) code