Click to See Complete Forum and Search --> : little-endian binary input


schecae1
September 24th, 1999, 09:09 AM
While Java by definition is big-endian, I've got to process binary data files that are written by little-endian machines. The files contain byte data (no problem) as well as 2 byte shorts, 4 byte ints, 4 byte floats and 8 byte doubles. I've written the routines do the byte swapping 'after' reading the InputStream. I'd like to know if there is a subclass of ObjectInputStream (e.g. LittleEndianObjectInputStream) to efficiently do the byte swapping for me with the readShort(), readInt(), readFloat(), and readDouble() routines.

Also, unlike C where I can create a char* that points to the data then efficiently swap the bytes in place, the only way I could figure out how to do this in Java was the following:


public static float readFloat( RandomAccessFile file, boolean bigEndian ) throws IOException
{
byte[] floatInBytes = new byte[ 4 ];
file.read( floatInBytes );
if ( ! bigEndian )
{
byte temp = floatInBytes[ 0 ];
floatInBytes[ 0 ] = floatInBytes[ 3 ];
floatInBytes[ 3 ] = temp;
temp = floatInBytes[ 1 ];
floatInBytes[ 1 ] = floatInBytes[ 2 ];
floatInBytes[ 2 ] = temp;
}
DataInputStream floatData = new DataInputStream( new ByteArrayInputStream( floatInBytes ) );
float value = floatData.readFloat();
return value;
}




Is there a more efficient way to do this?

Andrew Scheck
Laurel, MD
Andrew.Scheck@jhuapl.edu

veitas
September 24th, 1999, 09:34 AM
Here is a piece of code that will deal with it. It is located in the Language section of the codeguru.com/java site.


JAVA virtual machine always used big-endian, Intel x86 used little-endian.


public class Swab {
public final static int swabInt(int v) {
return (v >>> 24) | (v << 24) |
((v << 8) & 0x00FF0000) | ((v >> 8) & 0x0000FF00);
}

public static void main(String argv[]) {
// before 0x01020304
// after 0x04030201
int v = 0x01020304;
System.out.println("before : 0x" + Integer.toString(v,16));
System.out.println("after : 0x" + Integer.toString(swabInt(v),16));
}
}