I am using EMU8086. How do I add 4 digit numbers and display the sum in Assembly using one variable?
DATA SEGMENT
MSG1 DB "ENTER NUMBER WITH FOUR DIGITS : $"
MSG2 DB 10,13,"RESULT : $"
D1 DB ?
D2 DB ?
D3 DB ?
D4 DB ?
SUM DB ?
RES DB 10 DUP ('$')
DATA ENDS
CODE SEGMENT
ASSUME DS:DATA CS:CODE
START:
MOV AX,DATA
MOV DS,AX
LEA DX,MSG1
MOV AH,9
INT 21H
MOV AH,1
INT 21H
SUB AL,30H
MOV AH,0
MUL AL
MOV D1,AL
MOV AH,1
INT 21H
SUB AL,30H
MOV AH,0
MUL AL
MOV D2,AL
MOV AH,1
INT 21H
SUB AL,30H
MOV AH,0
MUL AL
MOV D3,AL
MOV AH,1
INT 21H
SUB AL,30H
MOV AH,0
MUL AL
MOV D4,AL
ADD AL,D3
ADD AL,D2
ADD AL,D1
MOV SUM,AL
LEA SI,RES
CALL HEX2DEC
LEA DX,MSG2
MOV AH,9
INT 21H
LEA DX,RES
MOV AH,9
INT 21H
MOV AH,4CH
INT 21H
CODE ENDS
HEX2DEC PROC NEAR
MOV CX,0
MOV BX,10
LOOP1: MOV DX,0
DIV BX
ADD DL,30H
PUSH DX
INC CX
CMP AX,9
JG LOOP1
ADD AL,30H
MOV [SI],AL
LOOP2: POP AX
INC SI
MOV [SI],AL
LOOP LOOP2
RET
HEX2DEC ENDP
END START
The question you ask does not entirely correspond to the code that you've written. If you were to add a couple of 4-digit numbers then you would of course have to input more than one such number! See the EXTRA section.
Therefore I conclude that you maybe just ill-phrased the question and I'll comment on the code you've shown:
Your program adds the 4 digits of a single 4-digit number. This means that the maximum result can ever be 9+9+9+9 which gives 36. This fact is important for the rest of the program since it effects the choice of instructions.
When you actually input the individual digits you immediately destroy them by squaring them using the mul al
instruction!
MOV AH,1
INT 21H
SUB AL,30H ; From "0".."9" to 0..9
MOV AH,0 <-- Don't do this
MUL AL <-- Don't do this
MOV D1,AL
There's no real point in moving the sum to the sum variable since it won't be used as such afterwards. But you do need to extend the AL register to the size of AX since the conversion routine expects AX as an input:
ADD AL,D3
ADD AL,D2
ADD AL,D1
MOV SUM,AL <-- Maybe not needed?
CBW <-- This clears AH (the high byte of AX) because AL is a very small number (less than 128)
LEA SI,RES
CALL HEX2DEC
I see you've chosen to have the conversion routine HEX2DEC to always display 2 decimal digits. This is fine.
EXTRA
To set you on the way for adding a couple of 4-digit numbers, I'll add the code to retrieve the first of these numbers. Make sure to define word sized variables in the DATA segment.
Calculation is based on this formula: Number= D1*1000+D2*100+D3*10+D4
Summing both numbers and displaying them should be a breeze!
NUM1 DW ?
NUM2 DW ?
SUM DW ?
...
MOV AH,1
INT 21H
SUB AL,30H
CBW
MOV DX,1000
MUL DX
MOV NUM1,AX
MOV AH,1
INT 21H
SUB AL,30H
CBW
MOV DX,100
MUL DX
ADD NUM1,AX
MOV AH,1
INT 21H
SUB AL,30H
MOV AH,10
MUL AH
ADD NUM1,AX
MOV AH,1
INT 21H
SUB AL,30H
CBW
ADD NUM1,AX
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.