MIPS 中的反向字符串
Reverse string in MIPS
我正在尝试编写一个程序来获取用户字符串输入并在 MIPS 中反转该字符串。
但是,我一定是做错了一些可怕的事情,因为它不仅反向显示用户输入,而且还反向显示给用户的提示。似乎用户输入最后没有用空(零?)字符标识。
.data
prompt: .asciiz "Please enter your name. You're only permitted 20 characters. \n"
userInput: .space 20 #user is permitted to enter 20 characters
.globl main
.text
main:
# user prompt
li $v0, 4
la $a0, prompt
syscall
# getting the name of the user
li $v0, 8
la $a0, userInput
li $a1, 20
syscall
add $t0, $a0, [=10=] # loading t0 with address of array
strLength:
lbu $t2, 0($t0)
beq $t2, $zero, Exit # if reach the end of array, Exit
addiu $t0, $t0, 1 # add 1 to count the length
j strLength
Exit:
add $t1, $t0, [=10=] # t1 = string length
li $t2, 0 # counter i = 0
li $v0, 11
reverseString:
slt $t3, $t2, $t1 # if i < stringlength
beq $t3, [=10=], Exit2 # if t3 reaches he end of the array
addi $t0, $t0, -1 # decrement the array
lbu $a0, 0($t0) # load the array from the end
syscall
j reverseString
Exit2:
li $v0, 10
syscall
问题编号 1:
add $t1, $t0, [=10=] #t1 = string length
您在这里分配给 $t1
的不是字符串的长度;它是 字符串末尾后第一个字节的 地址。
问题 2 是您永远不会在 reverseString
循环中递增 $t2
(或递减 $t1
)。
我建议您使用 SPIM/MARS 中的调试功能(例如设置断点和单步执行代码的功能),因为这将使您自己发现这些问题变得相当简单。
我正在尝试编写一个程序来获取用户字符串输入并在 MIPS 中反转该字符串。 但是,我一定是做错了一些可怕的事情,因为它不仅反向显示用户输入,而且还反向显示给用户的提示。似乎用户输入最后没有用空(零?)字符标识。
.data
prompt: .asciiz "Please enter your name. You're only permitted 20 characters. \n"
userInput: .space 20 #user is permitted to enter 20 characters
.globl main
.text
main:
# user prompt
li $v0, 4
la $a0, prompt
syscall
# getting the name of the user
li $v0, 8
la $a0, userInput
li $a1, 20
syscall
add $t0, $a0, [=10=] # loading t0 with address of array
strLength:
lbu $t2, 0($t0)
beq $t2, $zero, Exit # if reach the end of array, Exit
addiu $t0, $t0, 1 # add 1 to count the length
j strLength
Exit:
add $t1, $t0, [=10=] # t1 = string length
li $t2, 0 # counter i = 0
li $v0, 11
reverseString:
slt $t3, $t2, $t1 # if i < stringlength
beq $t3, [=10=], Exit2 # if t3 reaches he end of the array
addi $t0, $t0, -1 # decrement the array
lbu $a0, 0($t0) # load the array from the end
syscall
j reverseString
Exit2:
li $v0, 10
syscall
问题编号 1:
add $t1, $t0, [=10=] #t1 = string length
您在这里分配给 $t1
的不是字符串的长度;它是 字符串末尾后第一个字节的 地址。
问题 2 是您永远不会在 reverseString
循环中递增 $t2
(或递减 $t1
)。
我建议您使用 SPIM/MARS 中的调试功能(例如设置断点和单步执行代码的功能),因为这将使您自己发现这些问题变得相当简单。