How is this MIPS assembly conversion of this C pro

2019-08-30 18:55发布

问题:

I have a simple question for a Comp Sci class I'm taking where my task is to convert a function into MIPS assembly language. I believe I have a correct answer but I want to verify it.

This is the C function

int strlen(char *s) {
     int len;

     len=0;
     while(*s != '\0') {
          len++;
          s++;
     }
     return len;
}

Thanks!

strlen: 
    add $v0, $zero, $zero       
loop:
    lbu $t0, 0($a0)             
    addi $a0, $a0, 1            
    addi $v0, $v0, 1            
    bne $t0, $zero, loop        
s_end:
    addi $v0, $v0, -1           
    j $ra 

回答1:

Yeah, you have a correct asm version, and I like the fact that you do as much work as possible before testing the value of t0 to give as much time as possible for loading from memory.



回答2:

I think the while loop isn't right in the case of s = 0. It should be something like this:

    ...
    lbu    $t0, 0($a0)

loop:
    beq    $t0, $zero, s_end    # *
    ...
    b   loop

s_end:
    ...

*You could use a macro instruction (beqz $t0, s_end) instead of beq instruction.



标签: c assembly mips