0

我试图理解 MIPS 中的数组。我知道您需要将堆栈指针向前或向后移动一个单词(增量为 4)。但我不知道如何将这个想法实现到 MIPS 代码中。

 j = 0
 x = a[j+k]
 a[j+k] = a[j]

我确定的是将0加载到寄存器中(j = 0),然后我认为您将字加载到基地址$ a0并制作a [j],然后您将k添加到它之前,然后将该值添加到0($ a0)。

li $t0, 0       
lw $t0 0($a0)
add $t0, $t0, $a2
sw $t0, ($a0)

我们被指派将此代码转换为 MIPS,前一个是它的第一部分。

# Register usage
# $a0 = base address of array
# $a1 = n, size of array
# $a2 = k, the shift amount

# j = 0
# x = a[j+k]
# a[j+k] = a[j]
# repeat n-1 times
#   j = (j+k) mod n
#   m = (j+k) mod n
#   y = a[m]
#   a[m] = x
#   x = y
# end repeat

我的问题是如何在 MIPS 中进行 n-1 次循环?那么这是一个条件吗

subi $a1 $a1

最后如何找到mod?我相信它是 div 然后是 $HI。这就是我到目前为止所拥有的。

add $t1, $t0, $a2    #j+k
div $t1, $a1         #divide (j+k) by n
mfhi $t2             #move rem into t2
move $t2, $t0        #j = (j+k) mod n

add $t1, $t0, $a2    #j+k
div $t1, $a1         #divide (j+k) by n
mfhi $t2             #move rem into t2
move $t2, $t0        #m = (j+k) mod n

sw $t0, 0($t0)
lw $t3, 0($t0)

我相信我自己很困惑。澄清将不胜感激。

4

1 回答 1

1
li $t3, 0       #j = 0
lw $t3, 0($a0)     #load the value of @a0 in to j
add $t3, $t3, $a2  # j = j+k
sw $t3, 4($a0)     # store the new value of j in to $a0

loop:
beq $a1, $zero, return
sub $a1, $a1, 1      #n = n-1
add $t4, $t3, $a2    #j+k
div $t4, $a1         #divide (j+k) by n
mfhi $t5        

move $t5, $t3        #j = (j+k) mod n


 add $t4, $t3, $a2    #j+k
 div $t4, $a1         #divide (j+k) by n
 mfhi $t5             #move rem into t2
 move $t5, $t3        #m = (j+k) mod n
 b loop

return:
sw $t3, 4($a0)
jr $ra
lw $t3, 0($a0)

I saw your code here and after some tinkering. I had the program running but the outputs were wrong and i saw an error i made with the condition and upon fixing it the program no longer returns any out put. I changed the registers.

于 2012-04-07T01:40:08.507 回答