Search code examples
assemblymultiplicationmasm3216-bit

How to retrieve product of multiplication in Assembly?


For example, the code should basically do this: (1*10)+(2*10)+(3*10)+(4*10) = total

    xor bx, bx
    mov bx, 1

    loopHere:
        mov al, bx
        mov bl, 10
        mul bl
      ; add total, <product of bx and 10>
        inc bx
    cmp bx, 4
    jle loopHere

   ;some code to print the total

I read that the product goes to AX. However, I don't know how to retrieve the product in AX. At first, I tried typing

add total, ax

because it was the first obvious thing that popped into my mind but apparently I'm wrong. :P An error was detected saying 'invalid instruction operands' on the command prompt (I'm using masm32). Please help me understand. I'm just a newbie on assembly.

Also, if there's a more efficient way to do the code I'd happily take your advice. :) Thank you.


Solution

  • Since you're using al and bl for multiplication, you'll need to use a third register for storing the cumulative sum.

    add cx, ax ; don't forget to make sure cx is zero before you start
    

    Essentially, you didn't define a total variable, so you can't use it in your code. If there was a label named total pointing to a variable in memory, I think you could use that as well.

    add [total], ax
    

    In this case, you probably don't need a variable in memory, as a register will be sufficient, and faster.