MIPS汇编:INT到STRING函数只有2个字符(切掉最后一个字符)

时间:2016-01-19 08:21:29

标签: assembly mips qtspim

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

1 个答案:

答案 0 :(得分: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