Reverse order of bits in Java, or any other language

August 19th, 2006

At "Summercamp 2006" at the University of Passau I was working with pupils on a simple Voice over IP application. They finished this task quite fast and after two days we had to give them something more complex. So they worked on recording and manipulating sound.
Then we had the problem of changing the order of bits efficiently. I do not mean a simple xor, so I give you an example:

0 0 1 1 0 1 0 0 : 52 (changing order of bits)
0 0 1 0 1 1 0 0 : 44

I tried a few things with build in Java classes but did not find the solution. So I took a pencil and tried a lot with boolean operators. It turned out that you can restrict it to two lines of code, with a surrounding for statement:

for (int i = 0; i i< size; i++) {

    newInt = (newInt * 2 + (temp & 0x1));
    temp =  (temp / 2);
}

And because the members of our team where not familiar with these operators I wrote a whole Java class, which you can find here in my blog: BitFlip.java. The class requires a Java 5 compiler, because of the size constants. Feel free to use it in your projects.

Tags: ,

 

Entry Filed under: IT und Wissenschaft

1 Comment Add your own

  • 1. dajudge  |  September 5th, 2006 at 22:01

    or like this (untested):

    int newVal=0;
    for(int i=0; i<32; i++)
    newVal |= (val&(1<<i)) << (32- i-1);

    a good JITC should produce almost equal machine code though ;)

Leave a Comment

Required

Required, hidden

Summe von 3 + 8 ?

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Meistgelesen

Aktuelle Posts