Silicon to Scripting 8

Now that we know the algorithm for creating the Two’s Complement of a number, lets implement it in hardware.

  1. Start with the absolute value of the number
  2. Compute the bitwise inversion (invert all bits)
  3. Add 1 to the number, ignoring overflows

Increment

Just because it’s easier, lets start with INC.

We need to add 11 to a 16 bit number, ignoring overflow (ignore the carry).

We will need an ADD 16.

inc part 1

Now all we need is a 11, but how do we get it? Well we could invert a 0.

inc part 2

Note: I could have left out the “0” component because the default state of an inlet is disconnected, which is 0. I think it’s more clear the way I did it.

Subtraction

We need to compute ABA - B, which is A+(B)A + (-B), which means we need to complute the Two’s Complement of B.

  1. Start with the absolute value of the number: which is just B
  2. Compute the bitwise inversion: inv 16
  3. Add 1 to the number, ignoring overflows: inc 16

sub part 1

Now we can add them.

sub part 2

One thing to note is that even though adding to a very large number produces a negative number and vice versa, this is how computers today work. It’s a nasty bug that often gets caught in debug builds via explicit checking. — https://en.wikipedia.org/wiki/Integer_overflow

part 9