Convert C loop to MIPS

I am trying to make this C code translated directly into mips without changing any instructions so that it works better:

for(i = 0; i != j; i += 2)
    b[i] = a[i] - a[i + 1]

Actually, I'm not going to write in mips, I'm just trying to figure out some things. Here is what I have so far (not so much):

#t5 = i
$t6 = j
#t1 = a
#t2 = b
#t3 = c
#t10, t11, t12 = free

add $t5, $zero, $zero # initialize i = 0 

loop:
    bne $t5, $t6        # check if i is not equal to j
    addi $t5, $t5, 2    # i += 2
    add $t10, $t5, $t11 # temp reg $t10 = address of b[i]
    lw $t2, 0($t10)     # temp reg $t2 = b[i]
    add $t10, $t5, $t12 # temp reg $t10 = address of a[i]
    lw $t1, 0($t10)     # temp reg $t1 = a[i]

Not sure if correct bne, as I didn’t point anywhere to go to. I read on the arrays in my lips, but it bothers me. I know that I need to use the correct offset to address bytes when placing arrays in registers. Will it be the same with a variable instead of a number in an array? Any direction or advice would be nice. Thank!

+4
source share
2 answers

, . , . "exit".

, ; ( c). , ( ) . [i + 1] : a -, ( ) , . , , ; , , :)

#t5 = i
#t6 = j
#t1 = address of a
#t2 = address of b
#t10, t11, t12 = free

#START
move $t5,$0               #set $t5 to zero

loop:
       bne $t5,$t6,exit   #if $t5 not equal to $t6 branch to exit
       addi $t10,$t1,$t5  #temp reg $t10 = address of a[i]
       lw $t11,1($t10)    #temp reg $t11 = a[i + 1]
       lw $t12,0($t10)    #temp reg $t12 = a[i]
       sub $t10,$t12,$t11 #temp reg $t10 = a[i] - a[i + 1]
       addi $t11,$t2,$t5  #temp reg $t11 = address of b[i]
       sw $t10,0($t11)    #store word b[i] = a[i] - a[i + 2]
       addi $t5,$t5,2     #i+=2
       j loop             #jump to start of loop
exit:
+1

, 4 . Computer Organization and Architecture, , i, , :

sll $t10,$t5,2     #$t10=i*4
add $t10,$t10,$t1  #$t10 = i*4 + addr(a)
lw $t11,4($t10)    #temp reg $t11 = a[i + 1]
lw $t12,0($t10)    #temp reg $t12 = a[i]

, 4, lw 4. , , , . .

#t5 = i
#t6 = j
#t1 = address of a
#t2 = address of b
#t10, t11, t12 = free

#START
move $t5,$0               #set $t5 to zero

loop:
       bne $t5,$t6,exit   #if $t5 not equal to $t6 branch to exit
       sll $t10,$t5,2     #temp reg $t10 = i*4
       add $t10,$t10,$t1 #temp reg $t10 = address of a[i]
       lw $t11,4($t10)    #temp reg $t11 = a[i + 1]
       lw $t12,0($t10)    #temp reg $t12 = a[i]
       sub $t10,$t12,$t11 #temp reg $t10 = a[i] - a[i + 1]
       sll $t11,$t5,2     #temp reg $t11 = i*4
       add $t11,$t11,$t2  #temp reg $t11 = address of b[i]
       sw $t10,0($t11)    #store word b[i] = a[i] - a[i + 2]
       addi $t5,$t5,2     #i+=2
       j loop             #jump to start of loop
exit
+1

All Articles