简体   繁体   中英

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? 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.

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

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]

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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