best way to reverse bytes in an int in java
What's the best way to reverse t开发者_Go百科he order of the 4 bytes in an int in java??
You can use Integer.reverseBytes
:
int numBytesReversed = Integer.reverseBytes(num);
There's also Integer.reverse
that reverses every bit of an int
int numBitsReversed = Integer.reverse(num);
java.lang.Integer
API links
public static int reverseBytes(int i)
- Returns the value obtained by reversing the order of the bytes in the two's complement representation of the specified int value.
public static int reverse(int i)
- Returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified int value.
Solution for other primitive types
There are also some Long
, Character
, and Short
version of the above methods, but some are notably missing, e.g. Byte.reverse
. You can still do things like these:
byte bitsRev = (byte) (Integer.reverse(aByte) >>> (Integer.SIZE - Byte.SIZE));
The above reverses the bits of byte aByte
by promoting it to an int
and reversing that, and then shifting to the right by the appropriate distance, and finally casting it back to byte
.
If you want to manipulate the bits of a float
or a double
, there are Float.floatToIntBits
and Double.doubleToLongBits
that you can use.
See also
- Wikipedia/Bitwise operation
- Bit twiddling hacks
I agree that polygenelubricants's answer is the best one. But just before I hit that, I had the following:
int reverse(int a){
int r = 0x0FF & a;
r <<= 8; a >>= 8;
r |= 0x0FF & a;
r <<= 8; a >>= 8;
r |= 0x0FF & a;
r <<= 8; a >>= 8;
r |= 0x0FF & a;
return r;
}
shifting the input right, the output left by 8 bits each time and OR'ing the least significant byte to the result.
精彩评论