I wrote a program in assembly to ask the user to enter two numbers one by one and print the result on the console after performing addition on the two numbers. after compiling the program in x86 architecture, when I run the program, the program asks two numbers. but the problem is that, if I enter two numbers one-by-one, and the result of the consecutive numbers are grater than 9, it produces unexpected result on the screen. below I mention the steps, I go through, and face problem.
- below is a simple program, written in assembly code:
; firstProgram.asm
section .data
msg1 db "please enter the first number: ", 0xA,0xD
len1 equ $- msg1
msg2 db "please enter the second number: ", 0xA,0xD
len2 equ $- msg2
msg3 db "the result is: "
len3 equ $- msg3
section .bss
num1 resb 2
num2 resb 2
result resb 2
section .code
global _start
_start:
; ask the user to enter the first number
mov eax, 4
mov ebx, 1
mov ecx, msg1
mov edx, len1
int 0x80
; store the number in num1 variable
mov eax, 3
mov ebx, 0
mov ecx, num1
mov edx, 2
int 0x80
; print the first number
mov eax, 4
mov ebx, 1
mov ecx, num1
mov edx, 2
int 0x80
; ask the user to enter the second number
mov eax, 4
mov ebx, 1
mov ecx, msg2
mov edx, len2
int 0x80
; store the number, enter by the user in num2 variable
mov eax, 3
mov ebx, 0
mov ecx, num2
mov edx, 2
int 0x80
; print the second number, enter by user
mov eax, 4
mov ebx, 1
mov ecx, num2
mov edx, 2
int 0x80
; move the two numbers to eax and ebx register
; and subtract zero to convert it into decimal
mov eax, [num1]
sub eax, '0'
mov ebx, [num2]
sub ebx, '0'
;add two numbers
; and add zero to convert back into ascii
add eax, ebx
add eax, '0'
; store the number in result variable
mov [result], eax
; print a message to the user before printing the result
mov eax, 4
mov ebx, 1
mov ecx, msg3
mov edx, len3
int 0x80
; now print the result
mov eax, 4
mov ebx, 1
mov ecx, result
mov edx, 2
int 0x80
; exit the program
mov eax, 1
mov ebx, 0
int 0x80
- after written the code, I compiled and execute it on the terminal as follows:
nasm -f firstProgram.asm -o firstProgram.o
ld -m elf_i386 -s -o first firstProgram.o
./first
<blockquote>
please enter the first number:
5
please enter the second number:
3
the result is: 8please enter the first number:
6
please enter the second number:
4
the result is: :please enter the first number:
4
please enter the second number:
67the result is: :Aplease enter the first number:
25please enter the second number:
the result is: 5
</blockquote>
can anyone explain the reason with example?