MIPS reverse the bits code ( Converted from C code) ...But it is not working

2k views Asked by At

Here is the C code:

unsigned int reverse(register unsigned int x)
{
    x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));
    x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));
    x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));
    x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));
    return((x >> 16) | (x << 16));
}

And here is my MIPS assembly code:

.data

prompt:
    .asciiz " please enter a binary number of up to 8 digits: \n"

prompt2:
    .asciiz " / "

    .text
    .globl main

main:   

    la  $a0, prompt
    li  $v0,4
    syscall 
    li  $v0,5
    syscall
    move    $t3,$v0




    andi $t0,$t3,0xAAAAAAAA
    srl  $t1,$t0,1
    andi $t0,$t3,0x55555555
    sll  $t2,$t0,1
    or   $t3,$t2,$t1


    andi $t0,$t3,0xCCCCCCCC
    srl  $t1,$t0,2
    andi $t0,$t3,0x33333333
    sll  $t2,$t0,2
    or   $t3,$t2,$t1

    andi $t0,$t3,0xF0F0F0F0
    srl  $t1,$t0,4
    andi $t0,$t3,0x0F0F0F0F
    sll  $t2,$t0,4
    or   $t3,$t2,$t1

    andi $t0,$t3,0xFF00FF00
    srl  $t1,$t0,8
    andi $t0,$t3,0x00FF00FF
    sll  $t2,$t0,8
    or   $t3,$t2,$t1



    srl  $t1,$t3,16
    sll  $t2,$t3,16
    or   $t3,$t2,$t1


    la  $a0,prompt2
    li  $v0,4
    syscall

    move    $a0,$t3
    li  $v0,1
    syscall


    li  $v0,10
    syscall

I tried to convert the C code to MIPS but it is not working properly. The outputs are usually negative integers. Please help me to convert this code to MIPS assembly. What is wrong with my code?

2

There are 2 answers

0
chotighoti On

I'd suggest that you also try using a mips compiler to stop compilation after the assembly stage in case you're still getting trouble. You can then compare the code generated. I'd suggest compiling without optimisations.

This link should help you (assumning you have access to a mips compiler). How can I compile to assembly with gcc

0
Armali On

i was making a huge mistake. i was not expecting the outputs as ASCII code. when we enter 1 it equals to 00000031 and it means as binary bites 0000 0000 0000 0000 0000 0000 0011 0001.. but i thought the number 1 's binary bites equal to 0000 0001 ..That is why the outputs were different from what i was expecting.. – user3003505