binary - Obtaining reversed Integer in Java -


There is a method in Java that reverses the bit in an integer reversebits (). I wanted to try another implementation and I have it:

  public static in reverse (int no) {int num_rev = 0; For (Int i = 0; I > I) & amp; 1); If (((>>) & amp; 1)! = 0) {num_rev = num_rev | (Intel) Math.Po (2, Integer. SSE-I); }} Return num_rev; }   

The result is not num_rev correct. Anyone have any idea how to "rebuild" the value? Perhaps there is a better way to do this?

Thanks for any suggestions

Common ways to reverse the bit Will be through bit manipulation, and definitely no floating point math routine!

For example (nb: untested).

  int reverse (int x) {int y = 0; For (int i = 0; i <32; ++ i) {y & lt; & Lt; = 1; // mer space y = (X & 1); // copy LSB's x in the x> & gt; & Gt; = 1; // shift X correct} return y; }   

because x is moved right and y moved to the left that the x Eventually MSB becomes y .

A good (and well-known method) method is:

  unsigned infinite reverse (unsigned int x) {x = ((((x and xxaaaaaaa ) & Gt; & gt; 1) | ((x and 0x55555555)  gt; & gt; 16) | (x & lt; & lt; 16);) }   

This is actually a C code, but as in Java, the unsigned type of port is not in Java, by removing what you should do < Code> unsigned abilities and & gt; & Gt; & Gt; & gt; instead of & Gt; Use to make sure that you do not get any "sign extensions".

It changes every other bit , then every other pair of bits, then every other nybble , then every Second byte , and then finally the top and bottom 16-bit word It really works :)

Comments