在MIPS汇编中交换数组中的元素? (更清楚的)

时间:2013-07-22 10:59:54

标签: c arrays assembly mips swap

我知道有一个类似的问题here。我想把它看作是这个问题的延续,但更彻底。

以下是我想转换为MIPS 的C代码的相关部分:

int a = [100];
...
j = 0;
while (j<50){
    if (a[j] > a[99-j]) {
        tmp = a[99-j];
        a[99-j] = a[j];
        a[j] = tmp;
    }
    j = j+1;
}

(所以它基本上像反向一样)

到目前为止,我已经完成了 MIPS

    .data
array:  .word 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80,
     79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60,
     59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40,
     39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20,
     19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,0
    .text
    .globl main
main:   
    la  $s1, array  # $s1 = array address
    la  $s3, array
    li  $s0, 0      # j = 0
    lw  $t0, 0($s1) # $t0 = a[0]
    lw  $t1, 396($s3)   # $t1 = a[99]

while:  beq $s0, 50, end    # break from while loop once j = 50

if: blt $t0, $t1, iterj # if the if statement not satisfied, branch to iterj
    sw  $t1, 0($s1) # write to a[99-j]
    sw  $t0, 396($s1)   # write to a[j]

iterj:  addi    $s0, $s0, 1 # increment j
    addi    $s1, $s1, 4 # increment source address starting with j = 0
    addi    $s3, $s3, -4    # decrement source address starting with j = 99
    lw  $t0, 0($s1) 
    lw  $t1, 396($s3)   
    j   while
end:
我在MIPS中所做的

摘要

基本上,我尝试在$ s1中初始化数组,并尽力在其上进行交换。然后我意识到我还需要在[0]处递增源地址,同时在[99]处递减源地址。所以我想我不能只使用1个数组,然后我在$ s3中创建了一个相同的数组来处理它:

addi    $s1, $s1, 4 # increment source address starting with j = 0
addi    $s3, $s3, -4    # decrement source address starting with j = 99

现在是我需要帮助的部分:

代码按顺序从0到31(所有以十六进制形式显示在MARS中)然后31到1然后突然63到47工作(正确交换)。显然我做错了。 我只需要做的就是通过交换<0>返回0到63(十六进制)或0到99(十进制)。任何提示?

1 个答案:

答案 0 :(得分:2)

嗯,你要求两个阵列是错的,但是你得出了这样的结论。请记住,任何可以用C编写的东西当然都可以用汇编语言编写,所以你提供的C代码应该作为模型。

--- EDIT

我建议首先加载数组的地址,然后计算结束地址。

la   $t0 array
addi $t1 $t0 396 #last element of array

然后在循环体中:

lw  $t2 0($t0)
lw  $t3 0($t1)
sw  $t2 0($t1)
sw  $t3 0($t0)

addi $t0 $t0 4 
addi $t1 $t1 -4
blt  $t0 $t1 loop