我编写了这个函数来将 int 值转换为 ascii 字符串。但是当输入类似于 315 时,它会将 31 打印到字符串中。由于我不是组装专家,因此我将不胜感激。这是代码:(int_buf 是存储整数输入的位置,$a 是字符串输出)
itoa:
la $t0, int_buf # load buf
add $t0, $t0, 30 # seek the end
sb $0, 1($t0) # null-terminated str
li $t1, '0'
sb $t1, ($t0) # init. with ascii 0
li $t3, 10 # preload 10
beq $t8, $0, iend # end if 0
loop:
div $t8, $t3 # a /= 10
mflo $t8
mfhi $t4 # get remainder
add $t4, $t4, $t1 # convert to ASCII digit
sb $t4, ($t0) # store it
sub $t0, $t0, 1 # dec. buf ptr
bne $t8, $0, loop # if not zero, loop
addi $t0, $t0, 1 # adjust buf ptr
iend:
move $a1, $t0 # return the addr.
jr $ra # of the string
编辑:我发现问题不在函数中,因为它是在我之后将字符串打印到文件的方式中:
li $v0, 15
move $a0, $s6
move $t8, $s2
jal itoa
li $a2, 4 //problem was only 2 digits selected here!
syscall
当我将它设置为默认的 4 位数字时,如何防止该工具将空字符打印到我的文件中?