stud91
stud91

Reputation: 1854

Integer array indexing with MIPS assembly

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)

Upvotes: 2

Views: 3891

Answers (1)

Paul R
Paul R

Reputation: 213200

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.

Upvotes: 1

Related Questions