Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Advanced
Jul 8, 1999

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.

Henrik Falck
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date