MappedbyteBuffer.get() 将位置增加太多

MappedbyteBuffer.get() increments position by too much

我文件的相关部分是这样的:

82 0a 96 c9 82 0a 96 d3 00 66 13 08

我在mappedbytebuffer 中打开文件并将位置设置为开头。然后我这样做:

MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
...
buffer.position(packetInfos.get(idPacket).getStartPos());

//getting the time from the packet header
time = Math.addExact(Math.multiplyExact((long) buffer.order(ByteOrder.LITTLE_ENDIAN).getInt(), 1000), Math.floorDiv(buffer.order(ByteOrder.LITTLE_ENDIAN).getInt(), 1000));

//getting the source ip from the ip frame
buffer.position(packetInfos.get(idPacket).getStartPos() + PACKET_IPSOURCE_OFFS); // puts the buffers position at the part of the file shown above
source = byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get());

//getting the destination ip from the ip frame
destination = byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get());

byteToUnsigned 方法只是做:

public static int byteToUnsigned(byte b){
    return b & 0xFF;
}

源最终是:“130.10.150.211”,而它应该是“130.10.150.201”。 出于某种原因,get() 方法在大多数情况下会将缓冲区的位置递增 1,但在第三次之后递增 5?正如您可能已经猜到的那样,我正在尝试解码目标 ip,它在 "D3" 之后开始读取,结果为“0.102.19.8”


甚至在 byteToUnsigned 调用之前源 Ip 是“-126.10.-106.-45”。


通过这一行一步步调试后:

source = byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get());

观察 buffer.position() 和 buffer.get(),我可以看到以下内容:

所以位置正确递增,但是第 72 和第 77 之间的字节不知何故对缓冲区不可见?


Api 明确指出:

public abstract byte get()
Relative get method. Reads the byte at this buffer's current position, and then increments the position.

我错过了什么?

原来我是个大白痴。我没有注意到字节 82 0a 96 向右重复了几个字节。这是我不小心放置了缓冲区的位置。别担心,我很惭愧。