Given the following C code:

B[8] = A[i - j]

Assuming B = $s7, A = $s6, i = $s3 and j = $s4

What would the assembly code be?

sub $s3, $s3, $s4 # i - j
sll $s3, $s3, 2   # multiply the offset by 4 
add $s3, $s3, $s6 # add the offset to the base address. I'm hoping to get a new address as return. Correct?
lw $s3, 0($s3)    # load from the made up address
sw $s3, 16($s7)   # saves

I can't find a version of lw that takes a register as the offset. Is this correct?

Recommended Answers

All 2 Replies

That's correct. Generally speaking, while it would have been a lot easier for the programmer had they allowed register offsets, it would have also made for a more complicated hardware. Given that one of the original goals of MIPS was that it would not be designed for assembly programmers (it was optimized to make compilers easier to write), this wasn't seen as a major limitation.

As a practical upshot of this, instead of trying to change the offset, you generally just want to keep the offset at zero and use one of the scratch registers to hold the index. Why a scratch value? because these are almost certainly not going to values you need to hold on to, whereas the original values of the indices and offsets you may need later, so you don't want to overwrite them.

For the most part, what you wrote should do the trick, though I would warn against storing a loaded value into the same register you are using as the base address. Also, a word in MIPS is 32-bits long, or four bytes, so you need to multiply the index constant by 4, not 2. I would recommend make the following changes:

sub $t0, $s3, $s4
sll $t0, $t0, 2
add $t0, $t0, $s6
lw $t1, 0($t0)
sw $t1, 32($s7)

Note, however, that in most practical programming, you are dealing with values that are function local on the stack, so you would need another level of indirection in order to get the correct values. We can assume for the time being that you've already done this, and that the values in $s7 and $s6 are in fact the correct positions.

Hi, DainWeb.. I have a answer, Can you help me????
If array B have basic address that is 0x0FE3B128. What must I do??
Thanks so much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.