MIPS - Array in array index

好久不见. 提交于 2021-02-17 05:17:25

问题


What is the following C code in MIPS?

f = A[B[i]]

I'm told it can be done in 6 lines but can't quite figure out how. f is in $t0, i is in $t3, A[] is in $s0, and B[] is in $s1. All types are integer.

The best I am able to think of is

lw $t5, $t3($s0);  # Doesn't work because lw syntax doesn't accept a register as an offset
lw $t6, $t5($s1);
sadd $t0, $t6, $zero

Obviously this is wrong. How would i go about getting the correct offset for each line?

Thanks.


回答1:


There might be more efficient ways, but here's one way in 6 lines:

sll $t2,$t3,2    # t2 = i * sizeof(int)
addu $t2,$t2,$s1 # t2 = &B[i]
lw $t0,0($t2)    # t0 = B[i]
sll $t0,$t0,2    # t0 *= sizeof(int)
addu $s0,$s0,$t0 # s0 = &A[B[i]]
lw $t0,0($s0)    # t0 = A[B[i]]

Read a MIPS instruction set reference to get more information about what individual instructions do.



来源:https://stackoverflow.com/questions/18921044/mips-array-in-array-index

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