Question

My goal is to translate the C code below to MIPS assembly. I feel like I am missing a crucial part in my code. Can someone explain what I am doing wrong and what I need to do to fix the problem please?

Here is the C code:

char str[] = "hello, class";
int len = 0;
char *ptr = str;
while (*ptr && *ptr != ’s’)
   ++ptr;
len = ptr - str;

Here is my code so far:

.data
    myStr: .asciiz "hello, class"
    s: .asciiz "s"
main:
    la $t0, myStr
    la $t1, s
    lbu $t1, 0($t1)

loop:
    beq $t0, $t1, continue
    addi $t0, $t0, 1
    j loop

continue:
    sub $v0, $t0, $t1
Was it helpful?

Solution

Well, for a start, you're not loading the byte from myStr inside the loop.

Your lbu loads up the s character into $t1 before the loop starts but, inside the loop, you compare that with the address $t0.

What you need to do is to lbu the byte from $t0 each time through the loop and compare that with $t1.

I would think that this would be the fix though it's been a while since I've done any MIPS.

Change:

loop:   beq    $t0, $t1, continue
        addi   $t0, $t0, 1
        j      loop

into:

loop:   lbu    $t2, 0($t0)            ; get character at current string location.
        beq    $t1, $t2, continue     ; exit loop is it matches.
        beq    $0, $t2, continue      ; exit loop if it's null.
        addi   $t0, $t0, 1            ; continue loop with next character.
        j      loop

If your goal is to simply get C code converted to MIPS, you could just get a copy of a MIPS gcc compiler and run it through gcc -S and possibly at -O0 so you can understand the output :-)

That's probably the fastest way. Of course, if your intent is to learn how to do it by hand, you may want to ignore this advice, although it would still be handy for learning in my opinion.

OTHER TIPS

You're not loading bytes from A/myStr outside the loop, either -- you load the address, and increment it in the loop, but compare the address to the character 's' as opposed to the character at that address.

Nor do you ever compare that character to 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top