Actions

Two's complement

From Sonic Retro

Revision as of 19:51, 9 January 2008 by Aurochs (talk | contribs) (sp)

Two's complement is by far the most common method of representing signed numbers (those that can be either negative or positive) in computing. Any positive integer can be changed into a negative integer by taking its two's complement, and vice versa. Any signed number with a 1 in the highest bit position (the most significant bit, or MSB) is considered to be negative in this system.

Two's complement is calculated by taking the bitwise NOT of a number (or complementing it) and adding one to the result. Any overflow bits are ignored. For instance, the number 7 is represented by the eight-bit binary number 0000 0111. !7 would be 1111 1000, and adding 1 gives us 1111 1001, which would be interpreted as -7. We would calculate the two's complement of 0 as such:

!(0000 0000) = 1111 1111
1111 1111 + 1 = 1 0000 0000 = 0000 0000

The two's complement of 0 is 0. A negative zero is impossible when using two's complement.

Two's complement is used so widely because it is very simple and cheap to implement signed addition and subtraction. For example, let's take 5 + -3:

0101 + 1101 = 10010 = 0010

The intermediate result is 18, which seems incorrect. But dropping the overflow bit gives us the correct answer of 2. This works for any set of numbers. We can also use this property to subtract two numbers with an adder circuit, simply by taking the two's complement of the subtrahend.