How can I read or write binary files written in little-endian format?
Location: http://www.jguru.com/faq/view.jsp?EID=205923 Created: Sep 14, 2000 Modified: 2000-10-14 10:57:16.689 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by man sung jun (http://www.jguru.com/guru/viewbio.jsp?EID=200638 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 = is.read(); int b2 = is.read(); int b3 = is.read(); int b4 = is.read(); // 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.