Steven Jewel Blog RSS Feed

28 Dec 2013

Signed Integers

Of all that I learned during my computer science degree, the way that computers do signed integer math has stuck with me as the most amazing. It is fantasticly simple, and much better than any system I would have come up with.

The system used is called "two's complement". Here is an explanation using regular decimal numbers. Imagine that you have a four digit register that can store the numbers 0000 through 9999. 9999 + 1 results in 0000 and 0000 - 1 results in 9999. Now let's say that you want to do some math involving negative numbers, but without adding extra hardware paths to handle those cases.

What you can do is pretend that the upper half of the values are negative numbers. So 5000 through 9999 are actually -5000 through -1, respectively. You do a conversion for display to the screen, but while doing the actual math you can just use regular addition, subtraction, and multiplication, without any regard for the fact that some of the numbers are negative.

First, let's look at addition and subtraction. 200 - 300 results in 9900, which corresponds with -100. -100 + 103 is really 9900 + 0103, which results in 10003, which is truncated to 0003. Finally, 2 × -1 is represented as 0002 × 9999, which results in 19998, or 9998, which is -2.

When working in binary, all of the math works the same way.

Why does this matter? Because it means that the circuits involved can be much simpler, requiring less transistors and also can run much faster.