对集合x86中的数组求和.在输入的索引上 [英] Summing an array in assembly x86. On the inputted indexes

查看:41
本文介绍了对集合x86中的数组求和.在输入的索引上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在添加数组但在输入的索引上遇到一些麻烦.例如,用户输入4作为开始数组,输入6作为结束数组,因此我将不得不遍历array [4]到array [6]并包括在内.我不确定是否可以在ArraySum过程的.data中使用数组.我是否必须以某种方式将其推入程序?

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?

我正在为此使用Kip Irvine的外部库.

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

我的代码在这里:

 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

推荐答案

从ArraySum访问 array 应该没有问题,但是循环代码似乎是错误的. loop label 指令减少 ecx 寄存器,如果 ecx 不为零,则跳转到标签.此外, array 包含DWORD,这意味着当您访问其元素时,应将索引乘以4.总体而言,循环的代码应如下所示:

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]

这篇关于对集合x86中的数组求和.在输入的索引上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆