convert little Endian file into big Endian

how can i convert a liitle Endian binary file into big Endian binary file. i have a binary binary written in C and i am reading this file in Java with DataInputStream which reads in big endian format.i also had a look on ByteBuffer class but have no idea how to use it to get my desired result. please help.

thanks alot


Solution 1:

Opening NIO FileChannel:

FileInputStream fs = new FileInputStream("myfile.bin");
FileChannel fc = fs.getChannel();

Setting ByteBuffer endianness (used by [get|put]Int(), [get|put]Long(), [get|put]Short(), [get|put]Double())

ByteBuffer buf = ByteBuffer.allocate(0x10000);
buf.order(ByteOrder.LITTLE_ENDIAN); // or ByteOrder.BIG_ENDIAN

Reading from FileChannel to ByteBuffer

fc.read(buf);
buf.flip();
// here you take data from the buffer by either of getShort(), getInt(), getLong(), getDouble(), or get(byte[], offset, len)
buf.compact();

To correctly handle endianness of the input you need to know exactly what is stored in the file and in what order (so called protocol or format).

Solution 2:

You can use EndianUtils from Apache Commons I/O:

It has static methods like long readSwappedLong(InputStream input) that can do all the swapping for you. It also has overloads that uses a byte[] as input, as well as write counterpart (to OutputStream or byte[]). It also has non-I/O methods like int swapInteger(int value) methods that can do conversion of plain Java primitives.

The package also has many useful utility classes like FilenameUtils, IOUtils, etc.

See also

  • Most useful free third party Java libraries?

Solution 3:

The two functions below swap between the endianness of a 2 and 4 bytes.

static short Swap_16(short x) {

    return (short) ((((short) (x) & 0x00ff) << 8) | (((short) (x) & 0xff00) >> 8));
}

static int Swap_32(int x) {
    return ((((int) (x) & 0x000000ff) << 24)
            | (((int) (x) & 0x0000ff00) << 8)
            | (((int) (x) & 0x00ff0000) >> 8) | (((int) (x) & 0xff000000) >> 24));
}