I'm trying to use this code for multidigit addition in assembly using user input, but I'm not getting the correct result
SYS_EXIT equ 1
SYS_READ equ 3
SYS_WRITE equ 4
STDIN equ 0
STDOUT equ 1
segment .data
msg db "The sum is: "
len equ $-msg
msg2 db "Input num1: "
len2 equ $-msg2
msg3 db "Input num2:"
len3 equ $-msg3
lf db 0x0A
segment .bss
sum resb 40 ; 40 Bytes for an ASCII string
sum_len resd 1
number1 resb 40
number2 resb 40
num1_len resd 1
num2_len resd 1
section .text
global _start
_start:
; Output "input num1"
mov ecx, msg2
mov edx, len2
mov ebx, 1
mov eax, 4
int 0x80
;read ans store input1
mov eax, SYS_READ
mov ebx, STDIN
mov ecx, number1
mov edx, 3
int 0x80
lea esi,[number1]
mov ecx,4
call string_to_int
; Output "input num2"
mov ecx, msg3
mov edx, len3
mov ebx, 1
mov eax, 4
int 0x80
;read ans store input2
mov eax, SYS_READ
mov ebx, STDIN
mov ecx, number2
mov edx, 3
int 0x80
lea esi,[number2]
mov ecx,4
call string_to_int
; Addition
mov eax, [number1]
mov ebx, [number2]
add eax, ebx
; Convert the number to a string
mov edi, sum ; Argument: Address of the target string
call int2str ; Get the digits of EAX and store it as ASCII
sub edi, sum
mov [sum_len], edi
; Output "The sum is: "
mov ecx, msg
mov edx, len
mov ebx, 1
mov eax, 4
int 0x80
; Output sum
mov eax, 4
mov ebx, 1
mov ecx, sum
mov edx, [sum_len]
int 0x80
; Output Linefeed
mov eax, 4
mov ebx, 1
mov ecx, lf
mov edx, 1
int 0x80
; Exit code
mov eax, 1
mov ebx, 0
int 0x80
; Input:
; ESI = pointer to the string to convert
; ECX = number of digits in the string (must be > 0)
; Output:
;EAX = integer value
string_to_int:
xor ebx,ebx ; clear ebx
.next_digit:
movzx eax,byte[esi]
inc esi
sub al,'0' ; convert from ASCII to number
imul ebx,10
add ebx,eax ; ebx = ebx*10 + eax
loop .next_digit ; while (--ecx)
mov eax,ebx
ret
int2str: ; Converts a positive integer in EAX to a string pointed to by EDI
xor ecx, ecx
mov ebx, 10
.LL1: ; First loop: Save the remainders
xor edx, edx ; Clear EDX for div
div ebx ; EDX:EAX/EBX -> EAX Remainder EDX
push dx ; Save remainder
inc ecx ; Increment push counter
test eax, eax ; Anything left to divide?
jnz .LL1 ; Yes: loop once more
.LL2: ; Second loop: Retrieve the remainders
pop dx ; In DL is the value
or dl, '0' ; To ASCII
mov [edi], dl ; Save it to the string
inc edi ; Increment the pointer to the string
loop .LL2 ; Loop ECX times
mov byte [edi], 0 ; Termination character
ret ; RET: EDI points to the terminating NULL