Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top