0

I am trying to understand arrays in MIPS. I know that you need to move the stack pointer either forward one word or back (increments of 4). But I don't know how to implement that idea into MIPS code.

 j = 0
 x = a[j+k]
 a[j+k] = a[j]

What I know for certain is to load 0 into a register (j=0), then I think you load word the base address $a0 and make a[j], then you add k to it before sw that value into 0($a0).

li $t0, 0       
lw $t0 0($a0)
add $t0, $t0, $a2
sw $t0, ($a0)

We were assigned to convert this code to MIPS, and the previous was the first part of it.

# Register usage
# $a0 = base address of array
# $a1 = n, size of array
# $a2 = k, the shift amount

# j = 0
# x = a[j+k]
# a[j+k] = a[j]
# repeat n-1 times
#   j = (j+k) mod n
#   m = (j+k) mod n
#   y = a[m]
#   a[m] = x
#   x = y
# end repeat

My question is how do I do the n-1 times loop in MIPS? is it a condition then just

subi $a1 $a1

And finally how to find the mod? I believe it is with div and then the $HI. This is what I have so far.

add $t1, $t0, $a2    #j+k
div $t1, $a1         #divide (j+k) by n
mfhi $t2             #move rem into t2
move $t2, $t0        #j = (j+k) mod n

add $t1, $t0, $a2    #j+k
div $t1, $a1         #divide (j+k) by n
mfhi $t2             #move rem into t2
move $t2, $t0        #m = (j+k) mod n

sw $t0, 0($t0)
lw $t3, 0($t0)

I'm confusing myself I believe. Clarification would be appreciated.

1 Answer 1

1
li $t3, 0       #j = 0
lw $t3, 0($a0)     #load the value of @a0 in to j
add $t3, $t3, $a2  # j = j+k
sw $t3, 4($a0)     # store the new value of j in to $a0

loop:
beq $a1, $zero, return
sub $a1, $a1, 1      #n = n-1
add $t4, $t3, $a2    #j+k
div $t4, $a1         #divide (j+k) by n
mfhi $t5        

move $t5, $t3        #j = (j+k) mod n


 add $t4, $t3, $a2    #j+k
 div $t4, $a1         #divide (j+k) by n
 mfhi $t5             #move rem into t2
 move $t5, $t3        #m = (j+k) mod n
 b loop

return:
sw $t3, 4($a0)
jr $ra
lw $t3, 0($a0)

I saw your code here and after some tinkering. I had the program running but the outputs were wrong and i saw an error i made with the condition and upon fixing it the program no longer returns any out put. I changed the registers.

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

Comments

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.