an easier subtractor

Previously we looked at how to subtract numbers, using the same principle as our adder. This time, we’re going to cheat!

let’s think about clocks for a bit

Imagine you have a clock. It currently shows 4 PM, and you want to set it to 2 PM. You’d have to subtract 2 hours to get it where you want.

Now imagine your clock is broken, and won’t let you turn it back. You can still set the clock to the right time — just turn it forwards by 10 hours (for a 12-hour clock) or 22 hours (for a 24-hour clock).

This works for any amount of time. Instead of subtracting hours, we can add hours on instead. This works because clocks “wrap around” — eventually you hit the maximum value, and end up back at zero.

application

Remember when we constructed roonish, our invented language for writing numbers in binary? We specified that each number would be the same number of bits long, and we’d pad the start with as many 0s as we needed.

This had the consequence of imposing a maximum value on the numbers we can represent. If we decide all numbers are 4 bits long, our maximum value is 1111 (15).

What happens if we add 1?

At the lowest column, we get 1 + 1, giving us 0 with a carry. This carry means the next column is also 1 + 1, giving us 0 with a carry… and so on, until we’ve carried the 0 all the way to the highest column. As a result, we get 0000, with a leftover carry at the end.

In other words, in a 4-bit system, 15 + 1 = 0 — it “wraps around” like a clock. This is called modular arithmetic.

definition

modular arithmetic is when we define a maximum number, and going beyond this number wraps us back around to 0.

If we keep adding higher numbers, it behaves just like a clock. Whenever our result is 16 or higher, we keep subtracting 16 until we’re back in the acceptable range:

  • 15 + 2 = 17 = (16) + 1 = 1
  • 15 + 3 = 18 = (16) + 2 = 2
  • etc

complements

So if we want to calculate A - B, we can instead calculate A + C, where C is some other number related to B. We’ll call it the complement of B.

In the next tutorial, we’ll look at how we can find the complement of B, and how we can represent this all in binary.

continue