How to implement MUL using all the other instructions in assembly?

前端 未结 2 654
死守一世寂寞
死守一世寂寞 2021-01-22 06:46

Say I have implemented all the ADD, AND, SHF, JUMP, BR, LDW, LDB(load word load byte...) ........except MUL (multiple) instructions in an assembly machine. Now I want to write a

2条回答
  •  攒了一身酷
    2021-01-22 07:28

    The general idea is the same as you (should have) learned in school when you did "long multiplication", except we do it in binary instead of decimal. Consider the two examples below:

          1010        1234
        x 1100      x 2121
    ----------   ---------
          0000        1234
         0000        2468
        1010        1234
     + 1010      + 2468
     ---------   ---------
       1111000     2617314  
    

    The example on the right is base-10 (decimal) and the example on the left is binary. Observe that the only digits you must multiply the top factor by is either 0 or 1. Multiplying by zero is easy, the answer is always zero, you don't even have to worry about adding that in. Multiplying by one is also easy, it just a matter of knowing "how far over to shift it". But that is easy, it as far over as you had to look to check that bit.

    Start with a 16-bit working copy of your number, and a 16-bit accumulator set to zero. Shift the top number over and any time there is a one in the right-most digit you add the "working copy" to the accumulator. Whether or not there is a one or zero, you need to shift the "working copy" to the left one bit. When the "top" gets to zero you know you are done and the answer is in the accumulator.

    There are some optimizations you can use so that you don't need as many 16-bit registers (or 8-bit register pairs), but I'll leave you to work out the details.

提交回复
热议问题