将小端字节序文件转换为大端字节序文件。

10

如何将小端字节序的二进制文件转换为大端字节序的二进制文件。我有一个用C编写的二进制文件,并在Java中使用DataInputStream读取该文件,DataInputStream默认以大端模式读取。我也看了一下ByteBuffer类,但不知道如何使用它来得到我想要的结果,请帮忙。

非常感谢。


12
端序(Endian),不是印度(Indian)。详情请参考维基百科:http://en.wikipedia.org/wiki/Endianness - polygenelubricants
3
打开鸡蛋可能会变得很混乱,我看到了 :) - rsp
是的,你们说得对。匆忙之中可能会犯错误,但不用担心,我会从错误中学习更多。感谢指出我的错误。 - sajjoo
6个回答

14

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

要正确处理输入的字节序,您需要了解文件中存储的内容以及其顺序(也称为协议或格式)。


4
你可以使用EndianUtils这个库,它来自于Apache Commons I/O
它有静态方法,例如long readSwappedLong(InputStream input),可以为你完成所有的交换。它还有使用byte[]作为输入的重载方法,以及write对应方法(写入到OutputStreambyte[])。还有非I/O方法,如int swapInteger(int value),可以转换普通的Java原始类型。

这个包还有许多有用的实用类,如FilenameUtilsIOUtils等。

另请参阅


2
下面的两个函数可以交换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));
}

0

最近我写了一篇关于如何做到这一点的博客文章。介绍了如何在不同字节序之间转换二进制文件。在这里添加以供未来参考。

您可以使用以下简单代码完成此操作

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


0
我猜你应该读取每4个字节,然后简单地反转它们的顺序。

@Recurse 根据 http://en.wikipedia.org/wiki/Endianness 的说法,您可能指的是混合字节序或中间字节序。 - jvdneste

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接