jackie chen
jackie chen

Reputation: 17

How to store ascii values in array using mips?

Im writing a function that takes three arguments. $a0 is a positive int value and $a1 is an array and $a3 is the array size. I have to take the first argument and convert it to ascii decimal digit. then store that digit into the array. I keep doing this til there is no more digits to convert. I have to return the last array address and the last ascii value that I store (which I put in $v0 and $v1). What am I doing wrong ?

uitoa:

li $t0 , 0   
li $t1 , 10
li $t4 , 48
li $t8 , 0
for :
beq $a0,$t8,finished
div $a0,$t1
mfhi $t2 #remainder
mflo $a0
add $t3,$t2,$t4 # +48 to ascii
add $t6 , $t6 , $a1  #address of array?
sb $t3, 0($t6)
addi $t6,$t6,1 # increment array ?
addi $t0, $t0 ,1
j for

finished:

la $v0 , ($t6)
la $v1 , ($t3)

Upvotes: 0

Views: 2160

Answers (1)

Ped7g
Ped7g

Reputation: 16586

add $t6 , $t6 , $a1 is t6 = t6 + a1, but this is the first time you use the t6, so it's value is undefined (which luckily leads to "out of range" when you try to write a byte there, if it would by accident end in some writeable memory, you would just receive wrong result plus some random memory overwritten causing very likely all kind of weird behaviour elsewhere).

Also you would do that add every cycle in loop (adding the a1 address to previously set t6), so in second cycle you will be going off, even if you would set t6 to zero ahead.

For zero input you just skip to finished, but you don't store the single '0' character into array, and neither t6 and t3 is initialized (but used).

At finished la v1,(t3) will read memory? I think you intended just to copy t3 to v1? So use load from register (not sure about mips mnemonics, I never learned mips asm).

You use t0 for nothing.

And by dividing number by 10 in loop, you get the digits backwards, but it looks like fill up the array incrementally.

Overall it looks like you get some grasp what you should do, but started to emit instructions right away. Stop for a while and split your algorithm into few simple steps written in code as whole line comments, then go trough them for various tricky inputs (0, 1, 10, max_positive_int) and make sure the logic is OK (Rubber duck programming). Make additional notes under steps, which values they need, try to simplify that, take notes where they have to be initialized, and assign registers to them.

Then the rest will mean just to write instructions for those steps, and debug it in debugger to verify everything works as intended.

BTW, from your question it looks like you didn't bother to run it in debugger even once. That's not how assembly programming works, especially if you are just learning. This also qualifies you for downvotes of question (not showing enough effort before asking), although I don't care, I would rather downvote people not showing effort to understand answers.. :D

Upvotes: 1

Related Questions