convert little Endian file into big Endian

后端 未结 6 904
感动是毒
感动是毒 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:14

    I recently wrote a blog post on doing exactly this. On how you can convert binary files between endianness. Adding it here for future reference for anyone coming here.

    You can get this done from the following simple code

    FileChannel fc = (FileChannel) Files.newByteChannel(Paths.get(filename), StandardOpenOption.READ);
    ByteBuffer byteBuffer = ByteBuffer.allocate((int)fc.size());
    byteBuffer.order(ByteOrder.BIG_ENDIAN);
    fc.read(byteBuffer);
    byteBuffer.flip();
    
    Buffer buffer = byteBuffer.asShortBuffer();
    short[] shortArray = new short[(int)fc.size()/2];
    ((ShortBuffer)buffer).get(shortArray);
    
    byteBuffer.clear();
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    ShortBuffer shortOutputBuffer = byteBuffer.asShortBuffer();
    shortOutputBuffer.put(shortArray);
    
    FileChannel out = new FileOutputStream(outputfilename).getChannel();
    out.write(byteBuffer);
    out.close();
    

    For detailed information about how this works you can refer to the original blog post - http://pulasthisupun.blogspot.com/2016/06/reading-and-writing-binary-files-in.html

    Or the code is available at - https://github.com/pulasthi/binary-format-converter

提交回复
热议问题