Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to reverse bytes in an int in java

Tags:

java

What's the best way to reverse the order of the 4 bytes in an int in java??

like image 760
DEACTIVATIONPRESCRIPTION.NET Avatar asked Jun 27 '10 17:06

DEACTIVATIONPRESCRIPTION.NET


People also ask

How to reverse bits in a byte 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.

Can we convert byte to int in Java?

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.

Why are bytes reversed?

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.


1 Answers

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
like image 122
polygenelubricants Avatar answered Oct 08 '22 21:10

polygenelubricants