How do I access each word in Assembly?

浪子不回头ぞ 提交于 2019-12-18 09:37:46

问题


Given:

.data
arr: .word 2,5,1,3,4
len: .word 5
sum: .word 0

How would I access each word in "arr" such as 2, 3 and 4?

Eventually, what I would like to do is find a sum of all of the values in "arr", but I'm having difficulty iterating through "arr".

Thank you for your time!

Additional Info:

  1. I'm using eduMIPS64

回答1:


First load the address of the array into a register, then you can access the items with a constant offset. (Your assembler might support constructs such as lw $t0, arr+12 as convenience shorthand for this. See your manual.) For iteration, either increment the address register, or add another register containing the offset. Be sure to account for item sizes. Folling example is for 32 bit mips, adjust as necessary for 64 bit:

.data
arr: .word 2,5,1,3,4
len: .word 5
sum: .word 0

.text
.globl main
main:
    la $t0, arr
    lw $t1, 12($t0)     # load arr[3] using byte offset
    li $t1, 3           # index
    sll $t1, $t1, 2     # multiply by item size
    addu $t1, $t1, $t0  # add base address
    lw $t1, ($t1)       # load arr[3]

# iteration type 1
# for(i=len, ptr=arr; i != 0; i -= 1, ptr += 1)
# ... use *ptr ...
    la $t0, arr
    lw $t1, len         # load length
loop1:
    lw $t2, ($t0)       # load item
    # process item here
    addi $t0, $t0, 4    # add item size to pointer
    addi $t1, $t1, -1   # decrement counter
    bne $t1, $0, loop1  # if counter != 0, repeat

# iteration type 2
# for(i=0, i != len; i += 1)
# ... use arr[i] ...
    la $t0, arr
    lw $t1, len         # load length
    li $t2, 0           # index
loop2:
    sll $t3, $t2, 2     # multiply by item size
    addu $t3, $t3, $t0  # add base address
    lw $t3, ($t3)       # load item
    # process item here
    addi $t2, $t2, 1    # increment index
    bne $t2, $t1, loop2 # if index != len, repeat

(note these sample loops do not handle zero length array, add check if necessary)



来源:https://stackoverflow.com/questions/13653474/how-do-i-access-each-word-in-assembly

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