简体   繁体   中英

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"

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

  • Use meaningful names: A, B, and C will do in your context
  • Don't store every constant in memory
  • Replace division by a power of 2 with a shift to the right
  • Do respect the order of the operations, especially for subtraction where the order of the operands is important
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM