The subroutine int_to_string
works well when writing to a 10 bytes memory buffer (see here), but outputs a weird result after I modified it to write to a string.
Only the digit for the unit is correct (1
).
What is the issue here?
; sum of array elements (integers)
; and write to console
section .text
global _start
_start:
mov eax, 0
mov ebx, array
mov ecx, lena
loop:
cmp ecx, 0
je print
add eax, [ebx]
add ebx, 4
sub ecx, 1
jmp loop
print:
; convert integer to string
mov esi, msg
call int_to_string
; call write syscall
mov edx, lenmsg ; length of the string
mov ecx, msg ; address of the string
mov ebx, 1 ; file descriptor, in this case stdout
mov eax, 4 ; syscall number for write
int 0x80
; call exit syscall
mov eax, 1
int 0x80
; Input:
; eax = integer value to convert
; esi = pointer to string to store the digit characters
int_to_string:
add esi, lenmsg-2
mov ebx, 10
.next_digit:
xor edx, edx ; clear edx prior to dividing edx:eax by ebx
div ebx ; eax /= 10
add dl, '0' ; convert the remainder to ASCII
dec esi ; store characters in reverse order
mov [esi], dl ;
test eax, eax
jnz .next_digit ; repeat until eax==0
ret
section .data
array dd 10, 20, 30, 40, 501
lena: equ $-array ; length of array
msg db "The sum is .", 0xA
lenmsg: equ $-msg ; length of msg
CodePudding user response:
Your loop
decrements ecx by 1 each time, so ecx should be initialized with a count of elements. But you initialize it with lena
, which is a count of bytes, i.e. 4 times too large. So you add a whole bunch of extra garbage to your sum.
One fix would be to replace mov ecx, lena
with mov ecx, lena / 4
.