1. Overview

Computers think in binary: On-off, yes-no, true-false. How do computers translate electricity into arithmetic, though?

In this tutorial, we’ll learn how computers subtract binary numbers using a technique called two’s complement.

2. Binary Addition

Before getting to two’s complement, let’s quickly refresh our memory on how addition works in base 10 and in base 2.

We learn about base 10 in school. Of course, it’s the number system that we use every day.

When we add 1 to 9 in base 10, we get a number with a new “1” to its left: 10. +

And, when adding two numbers, this results in carrying sums larger than 9 into the next column:

10^2

10^1

10^0

2

4

5

+

5

———————

2

5

0

In binary, or base 2, each placeholder is a multiple of 2. So, the same equation in binary would be:

2^7

2^6

2^5

2^4

2^3

2^2

2^1

2^0

1

1

1

1

0

1

0

1

+

1

0

1

————————————————

1

1

1

1

1

0

1

0

Note again that we still need to carry, and computers come with special circuitry to handle that case.

3. Binary Subtraction

But, what about subtraction? In subtraction, we borrow instead of carrying:

2^7

2^6

2^5

2^4

2^3

2^2

2^1

2^0

1

1

1

1

1

0

1

0

(250)

1

1

1

1

0

1

0

1

– (245)

———————————————————-

0

0

0

0

0

1

0

1

= (5)

And computers could add that circuitry, too, but there’s a more effective way.

Basically, if we want to subtract two numbers, we could just turn the second one into a negative value and then add the two numbers together.

To further save on circuitry, computers do this with a technique called two’s complement.

4. Two’s Complement

To create a two’s complement number, we reverse the one’s and zero’s, then add one.

For our example above:

0 0 0 0 0 1 0 1

We first negate it:

1 1 1 1 1 0 1 0

And then add 1:

1 1 1 1 1 0 1 1

So how do we use this? Well, remember in our later arithmetic, we learned that subtracting is the same as adding a negative number. The same happens here:

  1 1 1 1 1 0 1 0 (250)
+ 1 1 1 1 1 0 1 1 +(-5)
-----------------
  1 1 1 1 0 1 0 1 (245)

If this were just a paper and pen problem, yes, we would have one more column with a “1” in it. But computer circuits are hexadecimal.

And, for our example, the 1 that would appear in the 2^8 position just drops off, which is what makes two’s complement a clever optimization.

5. Conclusion

In this short article, we discussed the concept of two’s complement that allows computers to have one set of circuits – adders – that do two jobs: addition and subtraction.


« 上一篇: 稳定排序算法
» 下一篇: 代码覆盖率