0

我编写了这个函数来将 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 位数字时,如何防止该工具将空字符打印到我的文件中?

4

1 回答 1

2

当我将它设置为默认的 4 位数字时,如何防止该工具将空字符打印到我的文件中?

计算字符串中的位数很容易。您知道 NUL 终止符的位置是int_buf+31因为它的itoa编写方式。因此,只需将其与您返回的地址之间的差异itoa

li $a2,int_buf+31
sub $a2,$a2,$a1  # a2 is now equal to the number of digits in the string
于 2016-01-19T10:01:53.747 回答