convert little Endian file into big Endian

后端 未结 6 903
感动是毒
感动是毒 2020-12-04 01:23

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

6条回答
  •  死守一世寂寞
    2020-12-04 02:27

    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).

提交回复
热议问题