I have this code:
INCLUDE Irvine32.inc
.data
arry BYTE ?
prompt1 BYTE "Enter first hex number: ",0
prompt2 BYTE "Enter second hex number: ",0
prompt3 BYTE "The sum is ",0
prompt4 BYTE "The sum is out of range ",0
prompt5 BYTE "Convert again? [y/n]: ",0
prompt6 BYTE "First number is invalid ",0
prompt7 BYTE "Second number is invalid ",0
.code
main PROC
ReadInput:
L1:
mov edx, OFFSET prompt1
call writeString
mov edx, 0
call readHex
call Crlf
mov ecx, eax
jmp L3
L2:
mov eax, 0
mov edx, OFFSET prompt2
call writeString
mov edx, 0
call readHex
call Crlf
mov ebx, eax
mov eax, 0
jmp L4
L3:
cmp ecx, 0FFFFh
JA L5
JBE L2
L4:
cmp ebx, 0FFFFh
JA L6
JBE addInt
L5:
mov edx, OFFSET prompt6
call writeString
mov edx, 0
call Crlf
jmp L1
L6:
mov edx, OFFSET prompt7
call writeString
mov edx, 0
call Crlf
jmp L2
addInt:
clc
mov ax, cx
add ax, bx
JC printError
jmp convert
; convert hex to string
convert:
mov ecx, 0
mov esi, 0
mov si, 4
mov cx, 10h
convertDigit:
dec si
mov dx , 0
div cx
cmp dx, 9h
JA convertLetter
add dx, 30h
jmp printSucess
convertLetter:
add dx, 37h
jmp printSucess
printError:
mov edx, OFFSET prompt4
call writeString
call Crlf
printSucess:
mov arry[si], dl
cmp ax , 0
JNE convertDigit
mov edx, OFFSET arry
add dx, si
call writeString
call Crlf
exit
main ENDP
END main
when I tried to print output i get this
Enter first hex number: ff
Enter second hex number: ff
1FEer first hex number: Press any key to continue . . .
as you can see, there was a part of prompt1, er first hex number
which stuck with the value of the sum 1FE
, why did this happen
the program loop edx register 3 times first time the value is E
, the second time is F
, and the third time is 1
, then it get to writeString to print output, which seems to be what the program suppose to be doing, at this point the edx value suddenly jump to 00405911
, why did this happen?
thank in advance for the help
Add a NULL-terminator to the converted string. You could do that right before the convertDigit
loop:
mov byte ptr [arry+4],0
By the way, you don't need div
when you're dividing by a power of two (like 16). You can use the faster bitwise AND and shift instructions:
mov dx,ax
and dx,15 ; dx = ax & 15 (== ax % 16)
shr ax,4 ; ax = ax >> 4 (== ax / 16)