如何将小端字节序的二进制文件转换为大端字节序的二进制文件。我有一个用C编写的二进制文件,并在Java中使用DataInputStream读取该文件,DataInputStream默认以大端模式读取。我也看了一下ByteBuffer类,但不知道如何使用它来得到我想要的结果,请帮忙。
非常感谢。
如何将小端字节序的二进制文件转换为大端字节序的二进制文件。我有一个用C编写的二进制文件,并在Java中使用DataInputStream读取该文件,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();
要正确处理输入的字节序,您需要了解文件中存储的内容以及其顺序(也称为协议或格式)。
EndianUtils
这个库,它来自于Apache Commons I/O:long readSwappedLong(InputStream input)
,可以为你完成所有的交换。它还有使用byte[]
作为输入的重载方法,以及write
对应方法(写入到OutputStream
或byte[]
)。还有非I/O方法,如int swapInteger(int value)
,可以转换普通的Java原始类型。
这个包还有许多有用的实用类,如FilenameUtils
,IOUtils
等。
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));
}
最近我写了一篇关于如何做到这一点的博客文章。介绍了如何在不同字节序之间转换二进制文件。在这里添加以供未来参考。
您可以使用以下简单代码完成此操作
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
在经过大量谷歌搜索后,我找到了一个包含SwappedDataInputStream类的Apache Jar文件。 org.apache.commons.io.input.SwappedDataInputStream。 这个类让我的结果更加准确。有关该类的完整详细信息,请参见。
http://commons.apache.org/io/api-1.4/org/apache/commons/io/input/SwappedDataInputStream.html