MIPS汇编语言整数转ascii码的函数

您所在的位置:网站首页 mips输出如何使换行 MIPS汇编语言整数转ascii码的函数

MIPS汇编语言整数转ascii码的函数

2023-07-28 12:08| 来源: 网络整理| 查看: 265

在用MIPS汇编语言编程时,有些情况下我们需要将整数转成字符串的形式操作,这里为大家提供了一个现成的函数,注释标的很详细,供大家使用。

上代码! string: .space 4 #one more space, or the following string will be printed toString: li $t2, 2 #the number of needed space -1. the number of digits won't exceed 3, so we only need 3 space. la $t3, string #the last digit locates in ($t3+2), which is ($t3+$t2) li $t5, 10 bgez $t0, notNeg1 #print without a '-' nop li $a0, '-' li $v0, 11 #print $a0 ('-') syscall neg $t0, $t0 #to positive notNeg1: div $t0, $t5 #divide 10 mflo $t0 #quotient mfhi $t1 #remainder addi $t1, $t1, 48 #the ascii of the remainder add $t4, $t3, $t2 #get the store location sb $t1, ($t4) #save ascii addi $t2, $t2, -1 #update the number of remaining space beqz $t0, printStr #the quotient is 0, finish nop b notNeg1 nop printStr: addi $t2, $t2, 1 #get the start number of bytes of the location of the string add $a0, $t3, $t2 #get the location of the string li $v0, 4 syscall jr $ra nop

虽然说是现成的,但是肯定不能拿过来直接用啦!毕竟是汇编语言,有些参数必须要改一下:

第一行分配的空间字节数。这里注意,你需要知道你想要转换的整数的最大十进制位数,不算正负号。比如这里我知道我要转换的整数在[-500, 500]之间,最多三位,转成ascii码最多需要3个字节,所以这里分配4个字节的空间,也就是3+1。为什么要这样,注释里也有说,如果你之后还有定义字符串,这样可以防止你打印的时候把后面的字符串一起打上去。所以如果你的整数最大n位十进制位,那么这里就分配n+1字节的空间。同理,toString的第一行,在整数最大n位十进制位的情况下,这里给$t2赋的值就是n-1。

使用方法很简单,把你要进行转变的整数存放在$t0中,然后用jal toString调用这个函数即可。注意这个函数使用的寄存器,不要出现寄存器冲突哦!

这里有个孪生兄弟!MIPS汇编语言整数二进制输出的函数

这里还有个孪生兄弟!MIPS汇编语言ascii码转整数的函数



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3