Home > Software engineering >  Write MIPS (32) assembly code to swap the contents of A[2] with B[2]
Write MIPS (32) assembly code to swap the contents of A[2] with B[2]

Time:09-27

Here's the homework question: Assume that register $s2 holds the base address in memory of array ‘A’ and register $s3 holds the base address in memory of array ‘B’. Write MIPS code to swap the contents of A[2] with B[2].

For clarification, we've only been taught I-type and R-type instructions and we only know basic sw, lw, add, and subtract, nothing more complex. I'm not sure if I understand lw and sw correctly. Here's my attempt:

    lw $t2, 8($s2)      #load A[2] into temp
    lw 8($s2), 8($s3)   #load B[2] into previous A[2], or is lw 8($s2), 8($s3) not allowed?
    sw $t2, 8($s3)      #store previous A[2] value into previous B[2], sw is reversed of lw right?

Here's another somewhat similar question, the difference is it's A[4] with A[9] within the same array and the obvious mistake is the lack of scaling by 4 bits assuming 32 bits, so 16 not 4 and 36 not 9. But to me this is more elegant, would this be correct syntax for an assembly swap? They also stored into a temp.

lw $t0, 4($s1) 
sw 4($s1), 9($s1)
sw 9($s1), $t0

Their given answer is this but I still want to know if one of the three statement answers would work, it's not as direct of a swap but I could still just do this:

  lw $t0, 16($s1)
  lw $t1, 36($s1)
  sw $t0, 36($s1)
  sw $t1, 16($s1)

CodePudding user response:

Looks like sw and lw can't have two memory operands which is why something like lw 8($s2), 8($s3) doesn't work! Here's the best answer, this time it's explained why it didn't work:

  lw $t0, 8($s2)    #load A[2] into temp
  lw $t1, 8($s3)    #load B[2] into temp
  sw $t0, 8($s3)    #store value of A[2] into B[2]
  sw $t1, 8($s2)    #store value of B[2] into A[2]
  • Related