MIPS 程序集对字符串的值求和



如何在MIPS汇编中用随机数汇总字符串的值?

我尝试了很多东西,它对我不起作用。

有人可以帮我吗?

.data
correct_number:     .asciiz     "1234 5678 9012 3456"
.text
la $t0, correct_number
add $t1, $t1, $zero     #Iterator = 0
add $t2, $t2, $zero     #Sum = 0
addi $t3, $t3, 15       #Size = 15
while:
bgt $t1, $t3, endwhile
sll $t9, $t1, 2     #4*i
addu $t9, $t9, $t0  #correct_number[i)
lw $t6, 0($t9)      #load the first byte
addu $s7, $s7, $t6
addi $t1, $t1, 1    #iterator + 1
j while
endwhile:
li $v0, 1       #Print the sum
la $a0, ($s7)
syscall 

错误的结果:-738593543

我假设您想查找correct_number中所有数字的总和(不包括空格(。对于"1234 5678 9012 3456"预期结果是66

在尝试MIPS代码之前,使用高级伪代码总是有帮助的。在这种情况下,这是几行——

sum = 0
$t0 = address of correct_number
while *correct_number is not 0:   // this way, you can avoid '#Size = 15' in your solution
ch = *correct_number
if ch is not space:
ch -= 48                      // convert the ASCII of digit to numeric value
sum += ch
correct_number++                // increment string pointer
// now sum contains the sum of all digits.

仍然需要将其转换为MIPS -

.data
correct_number:     .asciiz     "1234 5678 9012 3456"
.text
la   $t0, correct_number    # $t0 = address of correct_number
move $t2, $zero             # $t2 = Sum = 0
while:
lb   $t1, ($t0)             # $t1 = load the current byte
beqz $t1, endwhile          # did we reach end of string?
beq  $t1, ' ', continue     # if not, is current char space?
subi $t1, $t1, '0'          # if not, convert the digit char to its numeric value
add  $t2, $t2, $t1          # sum += numeric_value
continue:
addi $t0, $t0, 1            # correct_number++ (increment pointer)
j while                     # and loop
endwhile:
li   $v0, 1                 # $v0 = 1 to print integer in $a0
move $a0, $t2               # move Sum to $a0
syscall                     # and print it

li $v0, 10                  # exit program
syscall 

最新更新