0

I have an assignment and I don't understand how to turn C code to assembly.

Suppose you have an array of 12. Rearrange the contents of the array so they are sorted from smallest to largest (from A[0] to A[12]).**

Address: 12, 8, 4, 0

Data: 1, 6, 4, 2

So the end result should be: A[0]==1, A[4]==2, A[8]==4, A[12]==6

This is my C code:

int x, i=12;
while(A[i] < A[i-4])
{
x = A[i];
A[i] = A[i-4];
A[i-4] = x;
i -= 4;
}

So now I have to translate that code to mips but I'm stuck. This is what I've made so far:

addi $t1, $t1, 12   #$t1 = i
sll $t0, $t1, 2
add $t0, $t0, $s6   #$s6 = A[]

lw $t2, 0($s6)
lw $t3, 4($s6)
lw $t4, 8($s6)
lw $t5, 12($s6)
loop: 
slt $t6, $t5, $t4
bne $t6, 1 END
lw $t6, $t5
lw $t5, $t4
lw $t4, $t6
addi $t5, $t5, -4
addi $t4, $t4, -4
j loop
END

I know this isn't correct but I don't know how to make it work.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • "Turning C program to MIPS assembly", isn't that the job of the *compiler*? ;) – Some programmer dude Apr 08 '22 at 12:23
  • @Someprogrammerdude Sorry if the title is inaccurate, english is not my main language. – Johnnakos1000 Apr 08 '22 at 12:28
  • 1
    You have C code to start with -- that's good. But you should run & test the C code to make sure it works. It doesn't look quite right. – Erik Eidt Apr 08 '22 at 14:48
  • 1
    Your C doesn't look like a complete sorting algorithm. At best an inner loop of insertionsort or something? (I'm assuming it's C using byte offsets for arrays, not actual C checking elements 4 elements apart.) Also it has no loop exit condition to stop you from going off the end. – Peter Cordes Apr 08 '22 at 14:48
  • Your assembly code has is not an accurate translation of the C code. There's multiple loads before the loop, which the C code doesn't have. So, it's not going to run the same as the C code. Also, there's no such operation as `lw $t6, $t5`. The MARS assembler, for example, won't take that. – Erik Eidt Apr 08 '22 at 14:49
  • 2
    Once you have working C code, then translate each C language statement exactly as it stands. Don't try to improve while translating. If you want to make improvements, do them in C first, run & test to make sure it works. You loose the benefit of having working C code if you change the basics of the algorithm in the translation to assembly. – Erik Eidt Apr 08 '22 at 14:51
  • 1
    A tip: put a comment on each asm line and show the C operation you're trying to do. Some of my previous answers are similar: https://stackoverflow.com/a/52750900/5382650 https://stackoverflow.com/a/49467899/5382650 https://stackoverflow.com/a/39262902/5382650 Here is a full `mips` bubble sort impl: https://stackoverflow.com/a/34015394/5382650 – Craig Estey Apr 08 '22 at 20:53
  • What is the type of `A`? – MikeCAT Apr 09 '22 at 10:28

0 Answers0