pike93
pike93

Reputation: 1

MIPS Assembly: INT to STRING function only 2 chars (cut off last char)

I wrote this function to convert an int value to ascii string. But when the input is something like 315 it'll print 31 into the string. As I'm not an expert in assembly any help with this will appreciate. Here's the code: (int_buf is where the integer input is stored, $a is the string output)

 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

EDIT: I fount out the problem is not in the function, as it's in the way I print the string to a file afterwards:

li    $v0, 15
move  $a0, $s6      
move  $t8, $s2
jal   itoa
li    $a2, 4 //problem was only 2 digits selected here!
syscall

How can I prevent the tool from printing empty chars into my file when I set it to a default of 4 digits?

Upvotes: 0

Views: 1462

Answers (1)

Michael
Michael

Reputation: 58427

How can I prevent the tool from printing empty chars into my file when I set it to a default of 4 digits?

Calculating the number of digits in the string is easy. You know that the NUL-terminator characters is at int_buf+31 because of how itoa is written. So just take the difference between that and the address you get back from itoa:

li $a2,int_buf+31
sub $a2,$a2,$a1  # a2 is now equal to the number of digits in the string

Upvotes: 2

Related Questions