Trying to convert an asciiz 'integer' into an actual integer in MIPS

冷暖自知 提交于 2020-01-21 10:39:29

问题


Currently in $t0, there is an asciiz string however this string consists of only numeric characters, and I would like this to be stored as an integer so I can add a number to it. However the method I am trying does not seem to work.

I load the users input into $a0, then move that address to $t0, and then chop off a character, then I try using andi to mask the first four bits, but this gives a memory address out of bounds error, any suggestions?

EDIT:

now the code only prints out the first integer. Which is not what I want. I am trying to get the entire integer to be printed.

li $v0, 8 #read a string into a0
la $a0, input1
move $t0, $a0
syscall

addiu $t0,$t0,1
li $t1, 5
andi $t0,$t0,0x0F


#print int in t0
move $a0, $t0
li $v0, 1
syscall

回答1:


Code that parses a string entered by the user and convert into an integer.

.data
   msgerror: .asciiz "The string does not contain valid digits."
   input: .space 9 

.text
.globl main

main:
   li $v0, 8        
   la $a0, input        #read a string into a0
   move $t0, $a0
   syscall

   li $t3,0
   li $t4,9
   la $t0, input        #address of string
   lbu $t1, ($t0)        #Get first digit of string
   li $a1, 10           #Ascii of line feed
   li $a0, 0            #accumulator

   addi $t1,$t1,-48  #Convert from ASCII to digit
   move $a2, $t1         #$a2=$t1 goto checkdigit
   jal checkdigit
   add $a0, $a0, $t1      #Accumulates
   addi $t0, $t0, 1      #Advance string pointer 
   lbu $t1, ($t0)        #Get next digit

buc1:   
   beq $t1, $a1, print #if $t1=10(linefeed) then print
   addi $t1,$t1,-48  #Convert from ASCII to digit
   move $a2, $t1         #$a2=$t1 goto checkdigit
   jal checkdigit
   mul $t2, $a0, 10  #Multiply by 10
   add $a0, $t2, $t1      #Accumulates
   addi $t0, $t0, 1      #Advance string pointer 
   lbu $t1, ($t0)        #Get next digit 
   b buc1

print:  
   li $v0, 1            #print integer $a0
   syscall
   b end

checkdigit:
   blt $a2, $t3, error  
   bgt $a2, $t4, error
   jr $ra

error:
   la $a0, msgerror
   li $v0, 4            #print eror
   syscall

end:    
   li $v0, 10           #end program
   syscall


来源:https://stackoverflow.com/questions/32673182/trying-to-convert-an-asciiz-integer-into-an-actual-integer-in-mips

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!