Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

arrays - How do I access each word in Assembly?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...