0

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.

wema
  • 3
  • 2

2 Answers2

0

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.

Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
  • I have a follow up question because I forgot that mov al, bx also has an error, why is it an error? Is there a way around it? – wema Sep 15 '14 at 14:55
  • `bx` is 16 bits, and `al` is 8 bits. The width of both operands has to match, or it won't know how much data it actually needs to move. – Kendall Frey Sep 15 '14 at 14:58
0

This is a working 32bit solution:

xor esi, esi        ;// Clear esi (lower DWORD result)
xor edi, edi        ;// Clear edi (higher DWORD result)
mov ecx, 4          ;// Multiplicant
mov ebx, 10         ;// Multiplicator
COUNTER_LOOP:
    mov eax, ebx    ;// eax = Multiplicator
    mul ecx         ;// eax = Multiplicant * eax (Multiplicator)
    add esi, eax    ;// add lower DWORD result ("total") to esi
    adc edi, edx    ;// add higher DWORD result ("total") to edi
loop COUNTER_LOOP   ;// Multiplicant = Multiplicant - 1 => next loop

The result is stored in ESI (lower DWORD) and EDI (higher DWORD). But I recommend to read a good assembler book first, because it can be difficult to understand the details for beginners.

f6a4
  • 1,684
  • 1
  • 10
  • 13