views:

112

answers:

1

Hello, I'm writing a simple snippet of code for an assignment and I need to convert a decimal number to binary, octal, and hexadecimal. I have it working, but I realized afterwards that because of the algorithm I'm using, I print the binary number backwards. The strategy I was using was to print one digit at a time. I'm still a beginner so I figured this would be an easy way to avoid more intermediate issues. Unfortunately I didn't think it all the way through.

binary:   la        $a0, bType                            #binary function selected, notify user
          li        $v0, 4                                #print notification
          syscall
          la        $a0, in_val                           #ask user for input decimal number
          li        $v0, 4                                #print
          syscall
          li        $v0, 5                                #syscall read int
          syscall
          move      $t0, $v0                              #save input value to $t0
          li        $t1, 2                                #load 2 into $t1 to divide by 2
          li        $v0, 4
          la        $a0, bRes                            
          syscall                                         #print result tag
binLoop:  divu      $t0, $t1                              #LO = $t0/2, HI = $t0 % 2
          mfhi      $t2                                   #$t2 = HI (remainder)
          mflo      $t0                                   #$t0 = $t0/2 (quotient)
          move      $a0, $t2                              #store digit to print
          li        $v0, 1                                #Print digit
          syscall
          bgtz      $t0, binLoop                          #if input != 0, keep dividing
          j         main

Is there any way I can maybe store each digit into a string with a label and concatenate each digit on thereafter, then read the string backwards or something? Maybe there is a better suggestion you might be able to point me to.

Just note that the code works at this point by printing a single binary digit at a time, but in the reverse order which we want it. The program is supposed to be able to handle large numbers(like 20 binary digits long) so I can't store each digit in its own register. Thanks all!

A: 

You may want to store the computed values in memory, and then read them on reverse to print them. Use one spare register to keep the offset of digits in buffer (to print), say $a1, and let's suppose you will be storing the digits starting at memory address 0x1000. Then, instead of making the syscall to print the digit, just store it with something like this:

sw $t2, 0x1000($a1)
addiu $a1, $a1, 4

Now, when you finish processing the input data, you can traverse in reverse order the vector you made and print each digit:

addiu $a1, $a1, -4
lw $t2, 0x1000($a1)
# Now your code to print the digit

You would have to loop until $a1 reaches 0

gusbro