将小Endian文件转换为big Endian

如何将liitle Endian二进制文件转换为大Endian二进制文件。 我有一个用C编写的二进制二进制文件,我用Java读取这个文件,DataInputStream读取大端格式。我也查看了ByteBuffer类,但不知道如何使用它来获得我想要的结果。 请帮忙。

非常感谢

打开NIO FileChannel:

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

设置ByteBuffer字节顺序(由[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 

从FileChannel读取到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(); 

要正确处理输入的字节顺序,您需要确切地知道文件中存储的内容以及顺序(所谓的协议或格式)。

您可以使用Apache Commons I / O中的 EndianUtils

它有static方法,如long readSwappedLong(InputStream input) ,可以为您进行所有交换。 它还有使用byte[]作为输入的重载,以及write对应的(对OutputStreambyte[] )。 它还有非I / O方法,如int swapInteger(int value)方法,可以转换普通的Java原语。

该软件包还有许多有用的实用程序类,如FilenameUtilsIOUtils等。

也可以看看

  • 最有用的免费第三方Java库?

下面的两个函数在2和4字节的字节序之间交换。

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

我想你应该每4个字节读一次,然后简单地改变它们的顺序。

谷歌搜索之后我发现了一个带有SwappedDataInputStream类的apache Jar文件。 org.apache.commons.io.input.SwappedDataInputStream。 这堂课让我的成绩准确无误。 有关该课程的详细信息,请参阅。

http://commons.apache.org/io/api-1.4/org/apache/commons/io/input/SwappedDataInputStream.html

我最近写了一篇关于这样做的博客文章。 关于如何在字节序之间转换二进制文件。 将它添加到此处以供将来参考的人参考。

您可以通过以下简单代码完成此操作

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

有关其工作原理的详细信息,请参阅原始博客文章 – http://pulasthisupun.blogspot.com/2016/06/reading-and-writing-binary-files-in.html

或者代码可以在 – https://github.com/pulasthi/binary-format-converter获得