尝试将asciiz的“整数"转换为MIPS中的实际整数 [英] Trying to convert an asciiz 'integer' into an actual integer in MIPS

查看:182
本文介绍了尝试将asciiz的“整数"转换为MIPS中的实际整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前在$ t0中,有一个asciiz字符串,但是该字符串仅由数字字符组成,我希望将其存储为整数,以便可以向其添加数字.但是我尝试的方法似乎不起作用.

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.

我将用户输入加载到$ a0中,然后将该地址移至$ t0,然后截断一个字符,然后尝试使用andi屏蔽前四位,但这会导致内存地址超出范围错误,有什么建议吗?

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?

现在代码只打印出第一个整数.这不是我想要的.我正在尝试打印整个整数.

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

推荐答案

用于解析用户输入的字符串并转换为整数的代码.

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

这篇关于尝试将asciiz的“整数"转换为MIPS中的实际整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆