Convert a Little Endian to a Big Endian

Convert a Little Endian to a Big Endian

Java uses a big endian data structure, but Intel-based computers and some others use a little endian format. You may run into problems reading binary data saved in little endian format. This code converts a little endian int to a big endian. There is a lot of room for optimization if you want better performance.

 int intLEtoBE(int le) { int[] i = new int[4]; i[0] = le & 0xff; i[1] = (le >> 8) & 0xff; i[2] = (le >> 16) & 0xff; i[3] = (le >> 24) & 0xff; return ((i[0] 

This code is fairly easy. It gets a little harder when it comes to doubles. A double is stored in 8 bytes, but in the IEEE 754 floating-point "double format" bit layout. Fortunately, Java has a Double.longBitsToDouble() method, which converts the bits in which a double is stored to a value, otherwise it would be hard work. Java also has a method that does the reverse called Double.doubleToLongBits(). Here's a method of converting a little endian double, stored inside a long (which is also 8 bytes), to a big endian, Java double:

 double longLEtoDoubleBE(long le) { long[] l = new long[8]; l[0] = le & 0xff; l[1] = (le >> 8) & 0xff; l[2] = (le >> 16) & 0xff; l[3] = (le >> 24) & 0xff; l[4] = (le >> 32) & 0xff; l[5] = (le >> 40) & 0xff; l[6] = (le >> 48) & 0xff; l[7] = (le >> 56) & 0xff; return Double.longBitsToDouble((l[0] 

If you're using a DataInputStream, you should use the DataInputStream.readLong() method, and not readDouble(). Sun has said conversion to big endian will be supported in future versions of the DataInputStream class, but this technique will still be useful for applet programming.


Share the Post: