Question: what's the problem Convert string to an integer in MIPS. I coded getting a string and converting it to int. But whatever I put in,
what's the problem Convert string to an integer in MIPS.
I coded getting a string and converting it to int. But whatever I put in, the result is just -1. If I put in 123 the result is -1 and also if I put in -123 result is -1. I think the problem is string register, but I don't know where is the problem.
.globl main .data input : .space 30 .text main: li $v0,8 #get string la $a0,input li $a1, 30 syscall jal str2int # call the procedure str2int move $a0,$v0 # move the return value into $a0 li $v0,1 syscall # print the result li $v0, 10 syscall # Exit the program # register $v0(return value) str2int: # Check for sign lb $t0,0($a0) # load the first byte into $t1 beq $t0,'-',negint # if sign is -,goto negint beq $t0,'+',posint # if sign is +,goto posint j convert negint: li $t1,1 # set flag $t1 to 1(represents negative) add $a0,$a0,1 # goto next ASCII character j convert # goto convert posint: li $t1,0 # set flag $t1 to 0(represents positive) add $a0,$a0,1 # goto next ASCII character convert: li $s0,0 # sum=0 loop: lb $t0,0($a0) # load the ASCII character into $t1 beqz $t0,exitloop # if the character is null, exit the loop blt $t0,'0',fail # if $t1 is a non-digit character,return -1 bgt $t0,'9',fail sub $t0,$t0,48 # convert ASCII digit to decimal digit mul $s0,$s0,10 # multiply the previous sum with 10 and add $s0,$s0,$t0 # the converted digit to sum add $a0,$a0,1 # goto next ASCII character j loop # goto loop exitloop: beq $t1,0,copy # if sign is +, goto copy neg $s0,$s0 # if the sign is -, take negation of integer copy: move $v0,$s0 # store the converted integer into $v0 j return fail: li $v0,-1 return: jr $ra # return $v0 to main
exaple :)
input : 123 output 123 input : -32 output -32
this is correct answer
but now, my answer is
input :123 output : -1 input : -32 output : -1
i don't know what is my code's problem.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
