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

后端 未结 1 389
青春惊慌失措
青春惊慌失措 2021-01-28 14:52

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

相关标签:
1条回答
  • 2021-01-28 15:27

    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
    
    0 讨论(0)
提交回复
热议问题