1

For example,

$a0 is an index/pointer
$a1 is the address of the array base

I want to access each element of the array within a loop, perform an arithmetic operation to that element, then save it to the next. The index should increase +1 on each iteration.

For a simple example, I'm trying to square each previous element in the array. Initial hard coded values are INDEX[0]=0, ARRAY[0]=2. I've marked where I'm confused. I don't know how to make this variable for each loop.

       .data
INDEX: .space  4
       .align  2
ARRAY: .space  16
       .align  2

       .text
        la     $a0, INDEX
        la     $a1, ARRAY
        li     $t0, 0
        sw     $t0, ($a0)       # set INDEX[0]=0
        li     $t0, 2
        sw     $t0, ($a1)       # set ARRAY[0]=2

LOOP:
        lw     $t0, ($a0)
        sll    $t0, $t0, 2      # $a0 * 4 to get element offset
        lw     $t1, $t0($a1)    # STUCK HERE (1)
        add    $t1, $t1, $t1    # square
        lw     $t0, ($a0)
        add    $t0, $t0, 1
        sw     $t1, $t0($a1)    # AND HERE (2)
        add    $a0, $a0, 1

               ... keep looping if space remaining in $a1

(1) How do I save the element ARRAY[INDEX] to register $t1 without hardcoding the offset?

(2) How do I save the altered register $t1 to a specific element in the array: ARRAY[INDEX] = $t1

Since the indirect addressing will change on each loop, I want to avoid using 4($a1), 8($a1), etc.

Thank you.

4

1 に答える 1

1

You need to add the base address and index together. Something like this ought to work:

    sll    $t2, $t0, 2      # $a0 * 4 to get element offset
    add    $t2, $t2, $a1    # Add the array base address to the scaled index
    lw     $t1, ($t2)       # $t1 = ARRAY[index]
    add    $t1, $t1, $t1    # square
    add    $t0, $t0, 1
    sw     $t1, ($t2)       

Note that you're not actually squaring numbers - you're doubling them (t1 = t1 + t1). To square a number you'd multiply it by itself.

于 2013-03-27T06:15:45.623 に答える