Two's complement

Two's complement

The two-in-two representation, like the sign-magnitude representation, uses the most significant bit as a sign bit, making it easier to check whether the integer is positive or negative

Differs from the representation in sign-magnitude in the way of interpreting the bits remaining

Consider an n-bit A integer represented in add-on to two. If A is positive, the sign bit, a_{n-1} is 0. The remaining bits represent the magnitude of the number in the same way as in the sign-magnitude representation, i.e.:

\sum\limits_{i=0}^{n} 0^{n-2} \cdot a_i\text{ si }A\geq 0

The number 0 is identified as positive and therefore has a bit of sign 0 and a magnitude of all zeros. The range of positive integers that can be represented is, from 0 (all bits are 0) to 2^{n-1}-1 (all bits are 1). Any larger number would require more bits

For a negative A number, the sign bit, a_n-1 is 1. The remaining n-1 bits can take any of the 2^{n-1} Combinations. Therefore, negative integers can be represented from -1 to (-2)^{n-1}, I mean:

A=(-2)^{n-1}\cdot a_{n-1}

It would be desirable to assign the bits of negative integers in such a way that their arithmetic manipulation could be done in a direct way, similar to that of unsigned integers. In unsigned representation, to calculate the value of an integer from its bit expression, the most significant weight is 2^{n-1}

The general case would be to apply the formula:

A=(-2)^{n-1} \cdot a_{n-1} + \sum\limits_{i=0}^{n} 0^{n-2} \cdot a_i

Properties

  • Range of values
    (-2)^{n-1}\text{ a } 2^{n-1}-1
  • Number of representations of 0
    Only
  • Denial
    Run the Boolean plug-in for each bit and add 1 to the resulting bit pattern
  • Enlargement of the length in bits
    Extra positions are added to the left, filling them with the value of the original sign bit
  • Rule of overflow
    If two equal sign numbers (both positive or negative) are added, there is overflow if and only if, the result has an opposite sign
  • Rule for subtraction
    To subtract B from A, the complement is taken to two of B and added to A

Conversions

Example: Convert from decimal to two's complement

We're going to convert \pm 18 to two's complement, first we convert it to binary

Number Ratio Rest
\frac{18}{2} 9 0
\frac{9}{2} 4 1
\frac{4}{2} 2 0
\frac{2}{2} 1 0

So we have that the binary part is:

18_{(10} = 10010_{(2}

To find the -18 you have to use the denial of the 18

It runs the Boolean plugin of each bit within 1 word (remember that it is 8 bits), then we have:

18_{(10} = 00010010_{(2}
00010010 \rightarrow 11101101

Adds 1 to the resulting bit pattern

11101101+1=11101110

So we have to:

\begin{cases} 18_{(10} = 00010010_{(2} \\ -18_{(10} = 11101110_{(2} \end{cases}