0

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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow that makes incredible sense now. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.