CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Sep 1999
    Location
    MD, USA
    Posts
    2

    little-endian binary input

    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
    [email protected]

  2. #2
    Join Date
    Jul 1999
    Location
    Metro DC
    Posts
    32

    Re: little-endian binary input

    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));
    }
    }




Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured