我试图将以下 C 代码转换为 MIPS,但我无法理解您如何获取数组中的 [k-1]。
int vek[100];
main()
{
int k;
int first = vek[0];
for (k = 1; k < 100; k++)
{
vek[k - 1] = vek[k];
}
vek[k – 1] = first;
}
这是我到目前为止得到的:
.data
vek: .space 400
.text
main:
addi s0,zero,1 #k = 1
addi s1,zero.100 #value 100
la t1,vek #t1 as index in vek
add s2,t1,zero #first = vek[0]
L1:
bgt s0,s1,end #if k is bigger then 100 jump to end label
addi s0,zero,-1 #k-1
sll t2,s0,2 #t2 = 4*k next space in the array
这是我迷失 self 的地方,我不明白我应该如何翻译其余代码。由于网络上缺少 MIPS 教程,您是我最后的机会。如果有好心人能帮忙翻译一下代码的最后一部分,给我一个解释就好了。
P.S 这不是我要使用的东西,它只是考试中的一个问题示例。
最佳答案
下面是一个应该有效的简单实现,并逐行解释了正在发生的事情:
get_first:
lw $s0, vek # 1. Load the word stored at location 'vek' into $s0.
addi $s1, $zero, 0 # 2. Load zero into $s1. This will store an offset into 'vek', in bytes.
loop_1:
la $s2, vek($s1) # 3. Load the *address* of the $s1-th word of 'vek' into $s2. This is the location you want to write to.
addi $s1, $s1, 4 # 4. Advance the $s1 pointer to the next word in 'vek'.
lw $s3, vek($s1) # 5. Load the *value* of the $s1-th word of 'vek' into $s3. This is the value you want to copy.
sw $s3, ($s2) # 6. Store the value obtained in line 5 into the location obtained in line 3.
blt $s1, 400, loop_1 # 7. Repeat until we have iterated over all memory in 'vek'.
set_last:
sw $s0, vek + 396 # 8. Store the value obtained in line 1 into the end of 'vek'.
您可能可以使它更简洁,但我试图使它易于理解,而且自从我看到 MIPS 以来已经很长时间了。
关于循环和数组的 C 到 MIPS 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33395460/