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
Well, for a start, you’re not loading the byte from
myStrinside the loop.Your
lbuloads up thescharacter into$t1before the loop starts but, inside the loop, you compare that with the address$t0.What you need to do is to
lbuthe byte from$t0each 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:
into:
If your goal is to simply get C code converted to MIPS, you could just get a copy of a MIPS
gcccompiler and run it throughgcc -Sand possibly at-O0so 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.