Two's complement

From Citizendium
Jump to navigation Jump to search
This article is developing and not approved.
Main Article
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, first complement each of the bits, then add 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, in one's complement), which simplifies many things.

Positive two's complement numbers are identical to their unsigned equivalents, with the most significant bit being a zero. Note, however, that an unsigned binary number of width N bits can express a range of values from 0 to (2^N)-1, whereas the values of a two's complement number of width N span the range from - 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. Using a single-bit control signal (S), which is 0 for addition and 1 for subtraction, this can be done economically in hardware. The 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, and thereby performing a subtraction, instead of an addition.