What's the best way to reverse the order of the 4 bytes in an int in java??
The java. lang. Integer. reverse() method returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified int value.
The intValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as int.
Description. The Byte Reversal block changes the order of the bytes in the input data. Use this block when your process communicates between processors that use different endianness. For example, use this block for communication between Intel® processors that are little-endian and others that are big-endian.
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 linkspublic static int reverseBytes(int i)
public static int reverse(int i)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With