我在MIPS中编写了这段代码来计算用户输入的小写字母数:
.data
msg1: .asciiz
count_lower: .space 41
.text
.globl main
main:
la $a0, msg1 #load address of msg1 to store string
li $a1, 100 #msg1 is 100 bytes
li $v0, 8 #syscall for read str
syscall
add $s1, $0, $0 #interger to print later
la $t0, count_lower
sw $a0, 0($t0) #store input string in $t0
loop:
lb $t1, 0($t0) #load char from $t0
beqz $t1, exit #if no more chars, exit
blt $t1, 'a', else #This line and line below are for if char is not lowercase
bgt $t1, 'z', else
addi $s1, $s1, 1 #if char is lowercase, +1 to $s1
sll $t0, $t0, 8 #shift one byte to get to next char
sll $t1, $t1, 8 #shift one byte to get to next char
else:
sll $t0, $t0, 8 #shift one byte to get to next char
sll $t1, $t1, 8 #shift one byte to get to next char
j loop #jump back to loop
exit:
move $a0, $s1 #move interge to print into $a0
li $v0, 1 #print interger in $a0
syscall
li $v0, 10 #exit
syscall
但是当我运行它时,无论输入什么字符串,它都会打印整数“0”。任何人都可以帮我排除故障吗?我在代码中写了一些评论来解释我的思想过程。
编辑:
1 .data
2 msg1: .space 100
3 .text
4 .globl main
5 main:
6 li $v0, 8 #syscall for read str
7 la $a0, msg1 #load address of msg1 to store string
8 li $a1, 100 #msg1 is 100 bytes
9 move $t0, $a0 #save user input to $t0
10 syscall
11 add $s1, $0, $0 #interger to print later
12 add $t1, $0, $0 #initialize $t1
13 loop:
14 sb $t0, 0($t1) #store rightmost char into memory 0
15 lb $t1, 0($t0) #load char from memory 0 into $t1
16 beqz $t1, exit #if no more chars, exit
17 blt $t1, 'a', else #This line and line below are for if char is not
18 lowercase
19 bgt $t1, 'z', else
20 addi $s1, $s1, 1 #if char is lowercase, +1 to $s1
21 srl $t0, $t0, 8 #shift one byte to get to next char
22 add $t1, $0, $0 #re-initialize $t1
23 j loop #jump back to loop
24 else:
25 srl $t0, $t0, 8 #shift one byte to get to next char
26 add $t1, $0, $0 #re-initialize $t1
27 j loop #jump back to loop
28
29 exit:
30 move $a0, $s1 #move interge to print into $a0
31 li $v0, 1 #print interger in $a0
32 syscall
33 li $v0, 10 #exit
34 syscall
答案 0 :(得分:1)
这不符合你的想象:
sw $a0, 0($t0) #store input string in $t0
该指令仅将字符串的地址存储在($t0)
(即count_lower
的前4个字节中)。
我真的不明白为什么你需要两个缓冲区。只需读取您为系统调用8指定的同一缓冲区中的字符。
另外,您对msg1
的声明不正确。您的评论为#msg1 is 100 bytes
,但您的声明为msg1: .asciiz
,当然不会保留100个字节。这应该更改为msg1: .space 100
。