Two's complement

From Citizendium
Revision as of 21:23, 19 March 2008 by imported>J. Noel Chiappa (Add some examples, clarify the last para (on doing + and - with a single adder))
Jump to navigation Jump to search
This article is developing and not approved.
Main Article
Discussion
Definition [?]
Related Articles  [?]
Bibliography  [?]
External Links  [?]
Citable Version  [?]
 
This editable Main Article is under development and subject to a disclaimer.

Two's complement is a signed binary numbering system. It is one commonly used in low-level hardware implementations, due to the ease of designing adders and subtracters for it. While sometimes harder for people to understand and work with, it's easier for computers to use than one's complement.

To convert a binary number into its two's complement negative, one first complements each of the bits, and then adds one to the result, using normal binary unsigned addition. So, for example, the positive number 1 (expressed as ..0001, with any number of leading zero bits) turns into ..1110, and then into ..1111.

Notice that 0 (expressed as ..0000, similarly) turns into ..1111, and with the addition of the 'one', back into ..0000. I.e. unlike one's complement, two's complement does not have two different representations of zero (i.e. ..0000 and ..1111), which simplifies many things.

Positive two's complement numbers are identical to their unsigned equivalents, with the first bit being a zero. Note, however, that an unsigned binary number with N digits has a range from 0 to (2^N)-1, whereas a two's complement number spans - 2^(N-1) through 2^(N-1) - 1. (The asymmetry in the range is because the sole value for 0 comes from the 'positive' half of the number space.)

Use of a single hardware adder to perform both addition and subtraction of two's complement numbers is straightforward. Since subtraction is simply the addition of a negative (which is to say that A - B = A + (-B)), to perform subtraction the hardware only has to negate the second number, and then perform a normal addition. This can be done economically in hardware using a single control bit (S), which is 0 for addition and 1 for subtraction. This control bit is XORed with each bit of the B input before they are sent to the adder; it is also used as the carry-in for the least significant bit of the adder, thereby performing the "add one" second step of the two's complement negation of B. When S=0, the adder performs an addition of its two inputs. When S=1, each bit in in B is complemented, and 1 is added to the entire value, converting B to its negative, thereby performing a subtraction, instead of an addition.