Reputation: 181
I am working on a mips program to convert numbers from ascii string into integers, with the parameter that it should accept positive and negative integer decimal strings. I know this is a pretty common a assignment but I wasn't able to resolve my problems online. I was able to get some tips, but still receiving errors when trying to run the program.
Here is the code I have at this time:
main: # convert string to integer
li $t6, 0x00 # $t6 = 0
li $t7, 0x09 # $t7 = 9
li $v0, 0x00 # initialize $v0 = 0
move $t0, $a0 # $t0 = pointer to string
lb $t1, ($t0) # load $t1 = digit character
loop:
blt $t1, $t6, Done # char < 0
bgt $t1, $t7, Done # char > 9
subu $t1, $t1, $t6 # convert char to int
mul $v0, $v0, 10 # multiply by 10
add $v0, $v0, $t1 # $v0 = $v0 * 10 + digit
addiu $t0, $t0, 1 # point to next char
lb $t1, ($t0) # load $t1 = next digit
bne $t1, $0, loop # repeat if not end of string
jr $ra # return integer
Done: #exit program if string not a number
li $v0, -1 # return -1 in $v0
jr $ra
I am getting tons of errors trying to run this and I just have no idea why. This is my first time writing in mips so I don't have a feel for it. Any tips? Thanks!
I did fix the errors I could understand. There is no TA and no available tutors in my area. I'd really like help understanding this if possible. I'd love some constructive replies.
Upvotes: 0
Views: 3441
Reputation: 22585
The code you provided tries to convert unsigned (positive) integers from an asciiz buffer to an integer. It fails because you provided the wrong constants for digits '0 and '9'. '0' in the ASCII table uses code 0x30, and '9' uses code 0x39, or alternatively just use '0' and '9' to load those immediates.
Therefore, to fix your program you should use:
li $t6, '0' # $t6 = 0x30
li $t7, '9' # $t7 = 0x39
To allow the routine to correctly parse negative integers you would need to:
$v0 = $v0 * 10 + digit
you should issue $v0 = $v0 * 10 - digit
Upvotes: 1