How to solve multiplication in assembly

Viewed 54

Im new to assembly trying to figure arithmetic problems. How do u add, sub, mul, or div in assembly? preferable would like an example of all by chance and what does int 21h mean?

    section .bss
    num resb 2
    number resb 2
   
    product resb 2


section .text
    global _start

_start:

    mov eax,3            
    mov ebx,0            
    mov ecx,num    
    mov edx,2    
    int 80h           
    
 
    mov eax,3            
    mov ebx,0            
    mov ecx,number    
    mov edx,2  
    int 80h           

    
    
    mov al, [num]
    mov bl, [number] 
    mul bl 
    
    mov [product], ax 
    
  

    mov eax,4            
    mov ebx,1            
    mov ecx,product    
    mov edx,2    
    int 80h    
    



   
 

 
    mov eax,1            
    mov ebx,0            
    int 80h;
1 Answers

Your data sizes seem all mixed up. You're doing everything with word instructions, i.e. 16 bits, but all your actual values are single bytes. Unlike in higher-level languages, you can't specify the type of a variable and then assume that all operations will automatically respect that type. You have to code the correct instruction for the type in every single instance. For instructions with one register and one memory operand, the data size is inferred from the size of the register, e.g. al is 8 bits and ax is 16 bits.

In principle you can treat the buffer num1 as a 16-bit value, where the high byte would be the space character, but it's simpler to just use the byte that actually contains the digit and ignore the byte that contains the space.

A more correct way to write the part that loads the values and does the multiplication would be something like:

mov al, [num1]
mov bl, [num2]
mov cl, [num3]
sub al, '0'  ; note: 8-bit subtraction
sub bl, '0'
sub cl, '0'
mul bl       
; the result of the first multiplication is in ax.
; the low byte of ax is al, and we are assured that the
; result fits in 8 bits, so we can just use al as the input 
; for the next multiply
mul cl
; now the result is in al and you can proceed to compute the output characters.

There is no need to store the intermediate result back into memory as answer1. Registers are faster and more efficient to access than memory, and you can and should keep your data in registers as much as possible, writing to memory only when it's truly required.

Other optimizations are possible here but I've omitted them to keep the code easier to understand.

Related