简体   繁体   English

从 c 转换为 mips

[英]translation from c to mips

Can you help me to translate this piece of code from c to mips?你能帮我把这段代码从 c 翻译成 mips 吗? I have ane exam the next week but i cant do this part, its very hard to me:( Here its the code:下周我有一个考试,但我不能做这部分,这对我来说很难:(这是代码:

int A[4] = { 2, 3, 4, 5 };
int B[4] = { 1, 1, 2, 3 };
int C[4] = { 0, 0, 0, 0 };

void
main()
{
    int actualizacion = 1;

    updateValues(4);
    actualizacion = actualizacion + 1;
}

void
updateValues(int var)
{

    switch (var) {
    case 4:
        do {
            var = var - 1;
            A[var] = B[var] - C[var];
        } while (var != 0);
        break;

    default:
        var = var * 2;
        break;
    }
}

You didn't mention which IDE you're using (eg spim , mips , etc.).您没有提到您正在使用哪个 IDE (例如spimmips等)。 So, I used mars .所以,我用mars

In C, when you index into an array, the compiler computes the offset based on the size [in bytes] of the element (eg for an int , this is 4).在 C 中,当您对数组进行索引时,编译器会根据元素的大小 [以字节为单位] 计算偏移量(例如,对于int ,这是 4)。 So, if the code was:所以,如果代码是:

x = C[var]

The "effective" code would be: “有效”的代码是:

x = *(int *) (((char *) C) + (var * 4));

In assembler, we have to do the same thing.在汇编程序中,我们必须做同样的事情。

Here's the code with annotations:这是带有注释的代码:

    .data
A:  .word   2, 3, 4, 5
B:  .word   1, 1, 2, 3
C:  .word   0, 0, 0, 0

    .text
    .globl  main
# s0 -- actualizacion
main:
    li      $s0,1                   # actualizacion = 1

    li      $a0,4
    jal     updateValues

    addi    $s0,$s0,1               # actualizacion += 1

    li      $v0,10
    syscall

    .globl  updateValues
# a0 -- var (array index)
# t0 -- var << 2 (byte offset)
# t1 -- array address
# t2 -- B value
# t3 -- C value
updateValues:
    li      $t0,4
    bne     $a0,$t0,update_default

update_loop:
    addi    $a0,$a0,-1              # var -= 1
    sll     $t0,$a0,2               # convert index into byte offset

    la      $t1,B                   # base address of B
    addu    $t1,$t1,$t0             # add in byte offset
    lw      $t2,0($t1)              # load value

    la      $t1,C                   # base address of C
    addu    $t1,$t1,$t0             # add in byte offset
    lw      $t3,0($t1)              # load value

    sub     $t2,$t2,$t3             # B - C

    la      $t1,A                   # base address of A
    addu    $t1,$t1,$t0             # add in byte offset
    sw      $t2,0($t1)              # store value

    bnez    $a0,update_loop         # loop until var == 0
    b       update_exit

update_default:
    li      $t0,2
    mul     $a0,$a0,$t0             # var = var * 2

update_exit:
    jr      $ra                     # return

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM