assemblymasm32

masm32 addition subtraction division and multiplication


.data
msg_title db "Multiply"
A DB  4
B DB  2
C0 DB 4
C33 DB 24
C4 DB 2
C1 DB 4

buffer db 128 dup(?)
format db "(24 - A*C/4)/(2+C/A + B)= %d"
 
.code
start:

MOV AL, A
IMUL C0
IDIV C1
SUB AL, C33

MOV AL,C33 
CBW
IDIV A
MOV BL, C4
ADD BL, B
ADD AL, BL

        
MOV CL, AL      
MOV AL, BL      
CBW             

        
IDIV CL          

CBW       
CWDE      

 
invoke wsprintf, addr buffer, addr format, eax
invoke MessageBox, 0, addr buffer, addr msg_title, MB_OK
 
invoke ExitProcess, 0
 
end start

So the answer should be 2 but no matter which line I change it always gives 0 as the answer

I guess I'm having a problem with the addition part in the 2nd bracket

*"MOV AL,C33 *CBW *IDIV A *MOV BL, C4 *ADD BL, B *ADD AL, BL"


Solution

  • I don't see how your calculations relate to the formula in the format string.

    The calculation in the '1st bracket' is redundant as mov al,c33 overwrites AL. Additionally it subtracts in the wrong way.

    IDIV CL is probably a typo for IDIV C1. I don't see any setup for the CL register, but if you divide 10 (in AX) by the value 4 that is in C1, the quotient would be 2.

    EDIT

    The amended code now performs a valid division using CL but possibly uses the operands reversed. I can't judge this because my very first remark still stands!

    MOV CL, AL      ; AL is 10
    MOV AL, BL      ; BL is 4
    CBW
    IDIV CL         ; 4 / 10 produces 0
    

    CBW IDIV BL would divide 10 / 4 and produce 2.


    Full rewrite of the calculation

    A db 4
    B db 2
    C db 4
    
    ...
    
    mov  al, A     ; (24 - A * C / 4) -> BX
    imul C
    shr  ax, 2
    mov  bx, 24
    sub  bx, ax
    
    mov  al, C     ; (2 + C / A + B) -> AL
    cbw
    idiv A
    add  al, 2
    add  al, B
    
    xchg ax, bx  
    idiv bl
    

    In the end the result would be 20 / 5 producing 4.