MIPS组装错误数字 [英] MIPS Assembly wrong digit

查看:182
本文介绍了MIPS组装错误数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

la $a0, number
li $t3, 0     #Iterator = 0
li $v1, 0     #Sum = 0

while:
add $t1, $a0, $t3   #t1 = &A[i]

lb $t1, 0($t1)      # A[i]

beq $t1, $zero, endwhile

add $v1, $v1, $t1       # Sum

addi $t3, $t3, 1        # Iterator + 1

subi $v1, $v1, 48       # ???? Every digit is added with 48, so i have to subtract but why ???

j while
endwhile:

li $v0, 1       #Print the sum
move $a0, $v1 
syscall 

有人可以帮助我吗?为什么我必须用48减去每个数字才能得到正确的结果? 我不知道为什么它每次都会将48一直添加到我字符串中的数字上. 例如,我有一个字符串:"1234",如果我不用48减去每个数字,则结果为202.如果对每个数字减去48,则正确的结果为10.

Can someone pls help me. Why do i have to subtract every digit with 48 to get the right result? I dont know why its keep adding every time 48 to the digit from my string. As example i have the String: "1234" if i dont subtract every digit with 48 the result is 202. With subtraction of 48 for every digit the right result is 10.

推荐答案

给定一个数字作为字符串(例如"1234"),您试图获取所有数字的总和. "1234"字符串按照以下5个字节存储在MIPS内存中- 49、50、51、52、0

Looks like, given a number as a string (say "1234"), you are trying to get the sum of all the digits. "1234" string is stored as following 5 bytes in MIPS memory - 49, 50, 51, 52, 0

第0个字节-十进制49(ASCII为1)
第一个字节-十进制50(ASCII的2)等.
第n个字节-十进制0(ASCII空字符-表示MIPS字符串的结尾)

0th byte - decimal 49 (ASCII of 1)
1st byte - decimal 50 (ASCII of 2) .. etc.
nth byte - decimal 0 (ASCII of null character - indicates the end of a string to MIPS)

从您的代码中考虑这一行-

Consider this line from your code -

lb $t1, 0($t1)      # A[i]

这会将字节值加载到A [i].在第一次迭代中,它会存储49(ASCII码为"1")本身而不是 "1".

This loads the byte value at A[i]. In the first iteration, this stores 49 (ASCII of '1'), not '1' itself.

现在要从ASCII值中获取数字本身,我们需要从中减去ASCII值"0".

Now to get the digit itself from it's ASCII value, we need to subtract ASCII of '0' from it.

,即数字 d 的ASCII- 0 的ASCII = d 的数值(考虑一下).
现在 0 的ASCII是48.这就是您要减去的值.

that is, ASCII of digit d - ASCII of 0 = numeric value of d (think about it).
Now ASCII of 0 is 48. That is what you are subtracting.

在没有它的情况下,您最终将1、2、3、4的ASCII值相加,即49 + 50 + 51 + 52 = 202

In its absence, you end up summing the ASCII values of 1, 2, 3, 4, which is 49+50+51+52 = 202

这篇关于MIPS组装错误数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆