Swapping two elements in an array in MIPS assembly

2019-08-30 00:27发布

问题:

I'm trying to learns the MIPS ISA. If I want to do this function in MIPS:

A[2*i]=A[2*k+j];

How would I go about this? I would also appreciate any other content that I can read, i.e links where I can read up on how to solve this kind of problem.

回答1:

We can break this down to 2 parts:

  1. Calculate the addresses of A[2*i] and A[2*k+j]
  2. Assign the value at the second address to memory at the first address

I'm only going to address (ahem) #1.

To calculate the address of an array element, you need to know 3 things:

  1. The address of the start of the array
  2. The index of the element you want
  3. The size of the array elements

I assume you know how to compute, or just know, #1 & #3. That leaves #2, which involves simple arithmetic. (Since you haven't indicated how i, j & k are represented, I can't help too much there).

The final step, then, is to multiply the index by the size of an array element; this gives you the offset of your desired element from the start of the array. Add that to the address of the start of the array, and you have your element's address.

P.S. The code you're translating doesn't swap two elements; it copies one over the other.



回答2:

It's been a while, but this could be close. You'll never learn assembly language without trying youself. Make more examples and code them. More study material here .

# int calc(int *A, int i, int j, int k)
# {
#   return A[2 * i] = A[2 * k + j];
# }

# Args: a0=A, a1=i, a1=j, a3=k Rtn: v0
.text
.set nomacro
.set noreorder
.global calc
.ent calc
calc:
sll $t0, $a1, 3   ; t0 = i * 8
sll $t1, $a3, 1   ; t1 = k * 2
add $t1, $t1, $a1 ; t1 += j
sll $t1, $t1, 2   ; t1 *= 4
add $t0, $t0, $a0 ; t0 += A
add $t1, $t1, $a0 ; t1 += A
lw  $v0, 0($t1)   ; r = A[4 * (2 * k + j)]
sw  $v0, 0($t0)   ; A[4 * (2 * i)] = r 
.end calc