繁体   English   中英

将 C 程序转换为 MIPS 汇编语言程序

[英]Converting a C program into MIPS assembly language program

我正在尝试将 C 程序转换为 MIPS 汇编程序。 以下是我的程序 C 代码:(注意:Bulbs[number] 是一个数组,对于用户输入的“数字”,初始化为全零值)

for(int i = 1; i <= number; i++) 
            for(int j = 1; j <= number; j++) 
                if(j % i == 0) 
                    Bulbs[j-1] = (Bulbs[j-1] + 1) % 2; 

到目前为止,我所拥有的如下:

li $t0, 0                   #$t0 is set to 0 to be used as index for for loop1
li $t1, 0                  #$t1 is set to 0 to be used as index for for loop2

li $s2, 4                  #integer 4 is stored in s2
mult $s3, $s2              #input number($s3) is multiplied by 4
mflo $s4                   #result of multiplication is stored in $s4

loop1:
bgt $t0, $s4, end_loop1      #if t$0 > $s4(input number*4), exit loop1, 
                           #performing multiplication by 4 since word occupies 4 bytes
addi $t3, $t3, 1                #t3 is initialized to serve as "i" from for loop1
loop2: 
    bgt $t1, $s4, end_loop2 #if $t1 > (input number*4), exit loop2
    addi $t4, $t4, 1            #t4 is initialized to serve as "j" from for loop2
    div $t4, $t3
    mfhi $t5                #$t4 % $t3 is stored in $t5
    bne $t5, $zero, if_end  #checking for if condition

    if_end:
    addi $t1, $t1, 4        #increment $t1 by 4 to move to next array element
    j loop2                 #jump back to top of loop2

end_loop2:
addi $t0, $t0, 4            #increment $t0 by 4 
j loop1                     #jump back to the top of loop1

end_loop1:

我认为我的 for 循环实现有效,并且我准确地设置了 if 条件(如果我错了,请纠正我),但我不知道如何实现 'Bulbs[j-1] = (Bulbs[j- 1] + 1) % 2;' 在我的 if 条件之后行。 我是 MIPS 的新手,希望得到任何帮助或反馈!

我假设您在某处将Bulbs定义为数组。 然后

Bulbs[j-1] = (Bulbs[j-1] + 1) % 2;

应该翻译成类似的东西:

la   $t7, Bulbs    # Move base pointer of bulbs to $t7
add  $t7, $t7, $t1 # $t7 = &Bulbs[j]
lw   $t6, -4($t7)  # $t6 = Bulbs[j - 1]
addi $t6, $t6, 1   # $t6 = Bulbs[j - 1] + 1
andi $t6, $t6, 1   # $t6 = (Bulbs[j - 1] + 1) % 2
sw   $t6, -4($t7)  # Bulbs[j - 1] = $t6

这是基于此信息 我之前没有做过MIPS组装,但它是RISC,那么难吗? :)

顺便说一句,您的程序集翻译中似乎存在错误。 在 C 版本中,你的j从 1 开始,而在汇编版本中它似乎从 0 开始( $t1数组索引在第二行被初始化为 0,直到循环体之后才被修改)。 修复很简单 - 将其初始化为 4 而不是 0。

暂无
暂无

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

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