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] << 24) | (i[1] << 16) | (i[2] << 8) | i[3]); } 

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] << 56) + (l[1] << 48) + (l[2] << 40) + (l[3] << 32) + (l[4] << 24) | (l[5] << 16) | (l[6] << 8) | l[7]);} 

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.

See also  How IoT Tech Will Transform Logistics

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist