是否有现有的Java class 将存储的数据按偏移量和长度转换为整数?

Is there an existing Java class to convert data stored little-endian to integers by offset and length?

我有一个数据文件,它由小端顺序的各个字段组成。我知道每个不同字段的偏移量和长度是多少。是否存在将偏移量和长度转换为整数的现有 Java class?例如:17 00 00 00 53 43 43 41 11 00 00 00 AA 35 00 00。字节 1 到 4 (17 00 00 00) 是 0x00000017。

Guava 提供 LittleEndianDataInputStream class 可用于按小端顺序检索值。

您应该尝试按原样阅读。获取 4 个字节的块并将它们视为整数。我确定 JVM 已经处理数字小端(据我所知,所有 Intel/amd 都是如此)。

如果您的文件是原始字节文件,您可以使用 ByteBuffer to read the file in little endian mode, and then use asIntBuffer() to read out the ints through an IntBuffer. If you need to navigate the file, you can use srcChan.position(targetPosition); 跳到下一个 "field"。

try (RandomAccessFile srcFile = new RandomAccessFile("data/data.bin", "r");
     FileChannel srcChan = srcFile.getChannel();) 
{
    //    Careful with these casts if you have large files - channel size is a long
    ByteBuffer ib = ByteBuffer.allocate((int)srcChan.size());
    ib.order(ByteOrder.LITTLE_ENDIAN);
    srcChan.read(ib);
    IntBuffer fb = ((ByteBuffer)ib.rewind()).asIntBuffer();
    while (fb.hasRemaining())
        System.out.println(fb.get());
}

输出:

23
1094927187
17
13738

但是,如果您有一个包含一系列 space 分隔的十六进制字符串的文本文件(您的问题中文件格式不清楚),您将不得不添加一些技巧来读取它,但是一旦进入,您可以在小端模式下使用 ByteBuffer 再次读出整数。

一般流程是:

  1. inputString.split(" ")
  2. String 数组的每个元素转换为 byte[]
  3. 使用 ByteBuffer.wrap 包装结果 byte[] 并遍历 ints

它可能(未经过编译时测试)看起来像下面的样子(不使用 IntBuffer,只是为了展示另一种方法):

String input = "17 00 00 00 53 43 43 41 11 00 00 00 AA 35 00 00";
String[] source = input.split(" ");
byte[] sourceBytes = new byte[source.length];
for (int i = 0; i < source.length; i++) {
    sourceBytes[i] = (byte)Integer.parseInt(source[i], 16);
}
ByteBuffer bb = ByteBuffer.wrap(sourceBytes);
bb.order(ByteOrder.LITTLE_ENDIAN);
while (bb.hasRemaining())
    System.out.println(bb.getInt());

输出与第一种方法相同。

您可以使用 java.nio.IntBufferjava.nio.ByteBuffer 并结合 java.nio.channels.FileChannel 来读取数据。