简体   繁体   English

MIPS 程序集错误的数字

[英]MIPS Assembly wrong digit

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 

Can someone pls help me.有人可以帮助我。 Why do i have to subtract every digit with 48 to get the right result?为什么我必须用 48 减去每个数字才能得到正确的结果? I dont know why its keep adding every time 48 to the digit from my string.我不知道为什么它每次都会将 48 添加到我的字符串中的数字。 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”,如果我不用 48 减去每个数字,结果是 202。每个数字减去 48,正确的结果是 10。

Looks like, given a number as a string (say "1234"), you are trying to get the sum of all the digits.看起来,给定一个字符串形式的数字(比如“1234”),您正在尝试获得所有数字的总和。 "1234" string is stored as following 5 bytes in MIPS memory - 49, 50, 51, 52, 0 “1234”字符串在 MIPS 内存中存储为以下 5 个字节 - 49, 50, 51, 52, 0

0th byte - decimal 49 (ASCII of 1)第 0 个字节 - 十进制 49(ASCII 为 1)
1st byte - decimal 50 (ASCII of 2) .. etc.第一个字节 - 十进制 50(ASCII 为 2)...等。
nth byte - decimal 0 (ASCII of null character - indicates the end of a string to MIPS)第 n 个字节 - 十进制 0(空字符的 ASCII - 向 MIPS 表示字符串的结尾)

Consider this line from your code -考虑您的代码中的这一行 -

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

This loads the byte value at A[i].这将加载 A[i] 处的字节值。 In the first iteration, this stores 49 (ASCII of '1'), not '1' itself.在第一次迭代中,它存储 49('1' 的 ASCII),而不是'1' 本身。

Now to get the digit itself from it's ASCII value, we need to subtract ASCII of '0' from it.现在要从它的 ASCII 值中获取数字本身,我们需要从中减去 '0' 的 ASCII。

that is, ASCII of digit d - ASCII of 0 = numeric value of d (think about it).也就是说,数字d 的ASCII - 0 的ASCII = d 的数值(想想看)。
Now ASCII of 0 is 48. That is what you are subtracting.现在0 的ASCII 是 48。这就是你要减去的。

In its absence, you end up summing the ASCII values of 1, 2, 3, 4, which is 49+50+51+52 = 202如果没有它,您最终将 1、2、3、4 的 ASCII 值相加,即 49+50+51+52 = 202

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM