MIPS decimal to binary conversion code is working

2019-09-08 16:16发布

问题:

I have a project in mips and its about decimal to binary conversion I managed to write the code and its working fine but as you all know when we make decimal to binary conversion on paper we write result in reverse and thats the key point because my program writes 1 and 0 in normal order and because that it just prints on screen I cant give a command to reverse it.

How can I reverse it should I store varibles in array and reverse it or use stacks please my knowlage is very low(as you can see from the code) and I am stuck with it.Help me please.

.data
ms1_msg:.asciiz "Enter The Number:"
.text
.globl main
main:

la $a0,ms1_msg    
li $v0,4
syscall

li $v0,5          #user enters number and it is stored in t0
syscall
move $t0,$v0


addi $t1,$zero,1  #t1=1
addi $t2,$zero,2  #t2=2
add $t5,$zero,1   #t5=1
add $t8,$zero,$zero 

add $t6,$zero,$t0  #t6=1

loop1:            #trying to find the counter for loop 2

addi $t5,$t5,1    
div $t0,$t2       
mflo $t4          
beq $t4,$t1,loop2 
sub $t0,$t0,$t0   
add $t0,$t4,$t0
j loop1           

s

loop2:            #twith using the counter (t5) I define how many times loop should circle. 

    addi $t9,$t9,1    
    div $t6,$t2       
    mfhi $t7          
    mflo $t8          
    move $a0, $t7     
    li $v0, 1
    syscall
    beq $t9,$t5,exit
    sub $t6,$t6,$t6   
    add $t6,$t8,$t6 
    j loop2           

    exit:                                      
    li $v0,10       
    syscall

回答1:

Your title says "binary to decimal", but your description and code implies "decimal to binary", so I'll assume the latter.

There's no need for a buffer to display a number as a binary string. It's just a matter of shifting and masking, which you can do in any order you want.

For example, the following code would print a value in its binary representation, with the leading zeroes omitted:

uint32_t value = 1234;
bool foundAOne = false;
int bit = 31;

printf("%d in binary is ", value);

do {
    // Check the most significant bit (i.e. the "leftmost" bit)
    if (value & 0x80000000) {  
        foundAOne = true;        
        printf("1");
    } else {
        if (foundAOne || bit == 0) {
            printf("0");
        }
    }
    bit--;
    // Shift out the current msb and move all other bits one step
    // to the left
    value <<= 1;
} while (bit >= 0);

printf("\n");

Converting this into MIPS assembly should be a fairly simple task.



标签: mips