How can I read or write binary files written in little-endian format?

John Zukowski

In order to read multi-byte values, where you know the byte order is not in the Java standard big-endian format, you basically need to read the individual bytes yourself and rearrange them. For instance, the following will read in a 4 byte int and swap the byte order around.

// read four bytes
int b1 =;
int b2 =;
int b3 =;
int b4 =;
// combine them
int combined = (b4 && 0xFF) << 24 +
               (b3 && 0xFF) << 16 +
               (b2 && 0xFF) << 8) +
               (b1 && 0xFF);
When working with floating point numbers, the Float.floatToIntBits() and Float.intBitsToFloat() methods may prove helpful.

Writing is just doing things in the opposite order, splitting apart the int first, then writing the individual pieces.

0 Comments  (click to add your comment)
Comment and Contribute






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



About | Sitemap | Contact