Summing an array in assembly x86. On the inputted indexes

笑着哭i 提交于 2019-12-20 04:26:12

问题


Im having some trouble adding an array but on the inputted indexes. For example, the user inputs 4 as starting and 6 as ending array so I will have to loop through array[4] to array[6] and add the numbers inclusively. I'm not sure if i can use my array in .data in the my ArraySum procedure. Do i have to push it into the procedure somehow?

I am using Kip Irvine's external library for this.

My code is here:

 TITLE Assignment 7

    INCLUDE Irvine32.inc


.data
str1 BYTE "The array sum is:    ",0
start BYTE "Enter the Starting Index:  ",0
endinx BYTE "Enter the Ending Index:    ",0

array DWORD 4, 6, 2, 5, 6, 7, 8, 4
sum DWORD ?
j DWORD ?
k DWORD ?

.code
main PROC
    mov esi, OFFSET array
    mov ecx, LENGTHOF array

    mov edx, OFFSET start
    call WriteString
    call ReadInt
    mov j, eax
    mov esi, j


    mov edx, OFFSET endinx
    call WriteString
    call ReadInt
    mov k, eax
    mov ecx, k

    call ArraySum
    mov sum,eax
    call WriteInt

main ENDP

;---------------------------------------------------
ArraySum PROC
;sums an array falling within j..k inclusive
;---------------------------------------------------
    push esi
    push ecx

    mov eax, 0
L1:
    add eax, array[esi]
    add esi, TYPE DWORD
    loop L1

    pop ecx
    pop esi
    ret

ArraySum ENDP

END main

回答1:


You should have no problem accessing array from ArraySum, but it seems that the code for the loop is wrong. The loop label instruction decreases the ecx register and it jumps to the label if ecx is not zero. Also array contains DWORDs which means that when you access its elements you should multiply the index with 4. Overall the code for the loop should be something like this:

   ;; array max_index in ECX, i.e. length-1
    push ebx
    mov ebx, offset array
    xor  eax, eax                      ; sum = 0
    xor  esi, esi                      ; index = 0
L1:                                    ; do {
    add eax, dword ptr [ebx + esi * 4]  ; sum += array[idx] scaled index addressing
    inc esi
    cmp esi, ecx
    jle L1                             ; }while(i <= max_idx)

    pop ebx
   ; EAX = sum of array[0 .. ecx*4]


来源:https://stackoverflow.com/questions/29812954/summing-an-array-in-assembly-x86-on-the-inputted-indexes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!