5

I am trying to understand the underlying mathematics of two's complement. Googling the topic gives me a lot of articles on how to invert the digits and add one, and why computers use this system rather than more straight forward binary addition. However, none of the articles seem to go into underlying logic of the system.

I want to know why it works.

hjpotter92
  • 3,069
Avatrin
  • 1,615

1 Answers1

1

Somebody found out that $$2^{N-1} + 2^{N-2} + \dots + 2^0 = \sum_{i=0}^{N-1} 2^i = 2^N - 1.$$

Apparently, the sum can also be expressed as $$ \sum_{i=0}^{N-1} 2^i = \sum_{i=0}^{N-1} (a_i + \bar{a}_i) \cdot 2^i,$$

where $a_i$ is either $0$ or $1$ and $$\bar{a}_i = \begin{cases}1 & \text{if } & a_i = 0 \\ 0 & \text{otherwise.} \end{cases}$$

We will denote $a_i$ as a binary coefficient and $\bar{a}_i$ as its complement.

Introducing $w = \sum_{i=0}^{N-1} a_i 2^i$ as a natural number in the range $0 \dots 2^N-1$, the first equation can be rewritten as $$w + \bar{w} = 2^N - 1,$$

where $\bar{w} = \sum_{i=0}^{N-1} \bar{a}_i2^i$ denotes, again, $w$'s complement.

The above equation is equivalent to $$-w = \underbrace{\bar{w} + 1}_{\text{two's complement}} - 2^N.$$

From my understanding, what happens next is a convention, namely agree upon that the $N$-th bit of a negative number is set to $1$, where the remaining bits are encoded as the two's complement of its absolute value.

If you are to subtract $w$ from another natural number $v$ in the range $0 \dots 2^N-1$, the two's complement allows you to express this as an addition: $$v - w = v + (-w) = v + \underbrace{1 + \bar{w}}_{\text{two's complement}} - 2^N.$$

In case $v > w$, we have that $$v + (-w) = (w + \epsilon) + (-w) = \epsilon + \underbrace{1 + w + \bar{w}}_{2^N} \underbrace{- 2^N}_{N\text{-th bit}} = \epsilon > 0, $$

and the negative bit vanishes due to overflow.

In case $v < w$, we have that $$v + (-w) = (w - \epsilon) + (-w) = \underbrace{\underbrace{1 + w + \bar{w}}_{2^N} - \epsilon}_{<2^N} - 2^N = -\epsilon < 0, $$

and the negative bit remains.

Max Herrmann
  • 1,488