MIPS 查找字符串结尾

MIPS find end of string

我有以下 mips 代码(运行 它在 QTSPIM 中),它应该计算字符串中的字符数并打印它们。

其背后的逻辑非常简单,但并没有按预期工作。一切顺利,直到它到达字符串的末尾,然后它继续计数,即使我将每个元素与 $zero 进行比较以找到字符串的末尾 (\0)。

是不是我退出循环的条件有问题,还是my_string最后没有包含\0所以不会退出?

    .data
endl: .asciiz "\n"
my_string: .asciiz "thisisastring"
star: .asciiz "*"
str_end: .word 0
space: .asciiz " "

    .text
    .globl main

main:
    la $a0, my_string
    li $v0, 4
    syscall

    la $a0, endl
    li $v0, 4
    syscall

    la $t0, my_string   #   load mystring to $t0
    li $t1, 0           #   make $t1 = 0, character counter
    lb $t2, ($t0)       #   make $t2 point to the first character of "my_string"
    li $t3, 1           #   $t3 is the ++ register to go to the next character  
    li $t4, 0           #   character counter
    la $t5, str_end

cont:
    beqz $t0, print #   if [=10=] is found print and exit
    addi $t4, $t4, 1        #   increase the counter

    lbu $a0, ($t0)          #   print current character
    li $v0, 11
    syscall

    addi $t0, $t0, 1        #   go to next char
    #move $t2, $t0


    j cont

print:
    move $a0, $t4
    li $v0, 1
    syscall
    j exit

exit:
    li $v0, 10
    syscall

问题出在指令的顺序,代码的逻辑上。

这是没有冗余代码的更正版本:

    .data
endl: .asciiz "\n"
my_string: .asciiz "thisisastring"
str_end: .word 0

    .text
    .globl main

main:
    la $a0, my_string
    li $v0, 4           #   print the string
    syscall

    la $a0, endl        #   print endl
    li $v0, 4
    syscall

    la $t0, my_string   #   load mystring to $t0
    li $t1, 0           #   make $t1 = 0, character counter
    lb $t2, 0($t0)      #   make $t2 point to the first character of "my_string"
    la $t5, str_end

cont:
    lb $a0, 0($t0)          #   print current character
    beqz $a0, print         #   if [=10=] is found print and exit

    addi $t1, $t1, 1        #   increase the counter
    addi $t0, $t0, 1        #   go to next char

    li $v0, 11
    syscall

    j cont


print:
    move $a0, $t1
    li $v0, 1
    syscall
    j exit

exit:
    li $v0, 10
    syscall