I wanted to convert this C code into MIPS.
C Code:
f = A[B[h-g]]
We assume that h > g
and B[h-g] > 0
. h
, g
, f
are integers.
Also assume that f
is assigned to register $s0
, g
to $s1
, h
to $s2
.
Base addresses of A
-> $s6
and B
-> $s7
Here is my attempt:
sub $t0, $s2, $s1
mult $t0, $t0, 4
lw $t0, $t0($s7)
mult $t0, $t0, 4
sw $s0, $t0($s6)
It looks good, apart from the last line, which should most likely be:
lw $s0, $t0($s6)
Note that you should always comment your code, particularly so when it's asm, e.g.
sub $t0, $s2, $s1 ; t0 = h - g
mult $t0, $t0, 4 ; t0 = (h - g) * sizeof(int) = byte index into B
lw $t0, $t0($s7) ; t0 = B[h - g]
mult $t0, $t0, 4 ; t0 = B[h - g] * sizeof(int) = byte index into A
lw $s0, $t0($s6) ; s0 = A[B[h - g]]
Note also that you should always test your code - I would recommend using a simulator such as SPIM for this.