3
$\begingroup$

I am stumbling over the Exercise 2.3 of Chapter 2, i.e.:

For the following C statement, what is the corresponding MIPS assembly code? Assume that the variables f, g, h, i, and j are assigned to registers $s_0$, $s_1$, $s_2$, $s_3$, and $s_4$, respectively. Assume that the base address of the arrays A and B are in registers $s_6$ and $s_7$, respectively.

B[8] = A[i−j]; 

So, in the solution (https://github.com/dmohindru/cod5e/blob/master/solutions/CH02_Solution.pdf), it is indicated, that after calculating i-j and adding to the base address

sub t0, s3, s4 add t0, s6, t0 

the word is loaded by

lw t1, 16(t0) 

But why 16?

In my humble opinion, that should be either shifted left by two or multiplied by four

mul t0, t0, 4 lw t1, 0(t0) 

to regard the 4-byte offset.

Or am I wrong?

$\endgroup$

1 Answer 1

2
$\begingroup$

You are correct. The number of bytes of offset from the base address of array $A$ is $4*(i-j)$ and this multiplication by $4$ can be achieved by doing an sll (shift left) operation by two bits. Here's the assembly code for $B[8] = A[i-j]$:

sub $t0, $s3, $s4 #temp register $t0 = i - j sll $t0, $t0, 2 #temp register $t0 contains 4*(i-j) add $t0, $s6, $t0 #t0 = address of A[i-j] lw $t1, 0($t0) #t1 = A[i-j] sw $t1, 32($s7) #B[8] now equals A[i-j] 
$\endgroup$
3
  • $\begingroup$ Thanks, but this does not answer the original question of whether the solution given by the book is wrong. $\endgroup$ Commented Jul 23, 2024 at 15:20
  • 1
    $\begingroup$ @lordsnyder The solution in the book is wrong. First, i-j needs to be multiplied by 4. But even assuming the instruction takes care of that (i.e. takes the position rather than number of bytes as the operand), an offset of 16 bytes does not make sense. $\endgroup$ Commented Jul 26, 2024 at 8:25
  • $\begingroup$ Thank you, that answers my question. $\endgroup$ Commented Jul 31, 2024 at 5:41

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.