8bit
This code and an emulator to run it can be found at: https://github.com/wmvanvliet/8bit
In one of his video's, Ben Eater showed us a program to multiply two numbers. In short, to multiply by , you would add to the result times, using a loop:
If we were to compute in this manner, the loop would iterate 15 times. Can we do better?
Computer science text-books will tell you that multiplication is usually performed using a "shift and add" algorithm, which is the binary version of the "long multiplication" method of multiplying you may have learned in elementary school. This is how one would compute in binary using this method:
At least, that is how we were taught in Dutch elementary schools: multiply with the least significant digit first. According to Wikipedia, in German schools, they multiply using the most significant digit first:
As it turns out, the German method is more suited to our computer architecture, so we'll be using that. At any rate, this method is much faster, as it always loops 8 times (given our 8-bit numbers).
As the multiplication examples show, during an iteration of the loop, we only do three things with the binary numbers:
Our computer can do all of those things!
But Marijn, we don't have a left-shift instruction! Oh, but we do. Sort of. A number added to itself will left-shift that number:
Easy enough to create a left-shift instruction by modifying the microcode, but even in the original architecture, we can left-shift a number at a memory location like this:
When we left-shift a number, the carry-flag will tell us whether we just shifted a 1 or 0 out of the register, so we can use the jc
instruction to either add to the intermediate result or not.
Here's what I came up with, given the 16-bytes of memory that we have. There's not enough room for a counter to properly terminate the program after 8 iterations, so we'll just keep on running, but the output will keep displaying the proper result:
If you have Python installed, you can download the code and an emulator to try it out: