Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Assembly (http://www.programmingforums.org/forum20.html)
-   -   Reversing bits (http://www.programmingforums.org/showthread.php?t=44618)

Troncoso Apr 16th, 2012 9:35 PM

Reversing bits
 
I have an assignment to write a program in LC-3 assembly. I have to write several sub routines, one of them being to reverse the order of bits in a word and store the result in a register.
An example:

10010101 => 10101001

A mirror, if you will. I can think of a couple ways to do this. My issue comes when I need to store the bits back into a register. My plan is to use a nested loop:

:

word = 16 bit word

for (int i = 16; 16 > 0; 16--) {
        for (int j = 0; j < i; j++) {
                ADD word to itself to shift bits left by 1
        }
        AND word with x8000 to isolate high order bit
}


That's my pseudocode to get the job done. The issue comes after this
:

AND word with x8000 to isolate high order bit

At that point, after each inner loop completes, I have the correct bit. I just don't know how to properly add that to the register.

Sorry, if this sounds complicated. I'll really appreciate any help.

Troncoso Apr 16th, 2012 10:12 PM

Re: Reversing bits
 
I really do apologize for the double post, but I can't find the "edit" button anywhere.

Either way, I forgot to mention, the LC-3 ISA only includes AND, ADD, and NOT operations.

The Dark Apr 17th, 2012 2:09 AM

Re: Reversing bits
 
You could have another variable (or register) - call it bitVal - that starts at 1 and doubles (using add) each time around your i loop. bitVal would be the value of the current bit you want to add. Then if your isolated bit is non-zero, add the bitVal to your result register.
something like:
:

word = 16 bit word
bitVal = 1
for (int i = 16; 16 > 0; 16--) {
        for (int j = 0; j < i; j++) {
                ADD word to itself to shift bits left by 1
        }
        AND word with x8000 to isolate high order bit
        if (word != 0)
          ADD bitVal to register
        ADD bitVal to itself to shift bits left by 1
}


Troncoso Apr 17th, 2012 3:25 AM

Re: Reversing bits
 
Dude! Thanks a lot. You gave me the idea that got my program working. It's basically what you did, except I put your

:

ADD bitVal to itself to shift bits left by 1

In the inner loop

:

word = 16 bit word
bitVal = 1
for (int i = 16; 16 > 0; 16--) {
        for (int j = 0; j < i; j++) {
                ADD word to itself to shift bits left by 1
              ADD bitVal to itself to shift bits left by 1
        }
        AND word with x8000 to isolate high order bit
        if (word < 0)
                ADD bitVal to counter
}


Still, I wouldn't have thought of that without you. Thanks again!


All times are GMT -5. The time now is 7:32 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC