There is a method in Java that reverses bits in an Integer reverseBytes(). I wanted to try another implementation and this is what I have:
public static int reverse(int num) {
int num_rev = 0;
for (int i = 0; i < Integer.SIZE; i++) {
System.out.print((num >> i) & 1);
if (((num >> i) & 1)!=0) {
num_rev = num_rev | (int)Math.pow(2, Integer.SIZE-i);
}
}
return num_rev;
}
The result num_rev is not correct. Does anyone have any idea how to “reconstruct” the value? Maybe there is a better way to perform it?
Thanks for any suggestions.
The normal way would to reverse bits would be via bit manipulation, and certainly not via floating point math routines!
e.g (nb: untested).
Because
xis right shifted andyleft shifted the result is that the original LSB ofxeventually becomes the MSB ofy.A nice (and reasonably well known) method is this:
This is actually C code, but as Java doesn’t have
unsignedtypes to port to Java all you should need to do is remove theunsignedqualifiers and use>>>instead of>>to ensure that you don’t get any “sign extension”.It works by first swapping every other bit, then every other pair of bits, then every other nybble, then every other byte, and then finally the top and bottom 16-bit words. This actually works 🙂