MappedbyteBuffer.get()增加位置

时间:2017-04-06 11:59:58

标签: java increment memory-mapped-files mappedbytebuffer

我档案的相关部分是:

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(),我可以看到以下内容:

  • first get():buffer.position()= 70,buffer.get()= - 126
  • second get():buffer.position()= 71,buffer.get()= 10
  • third get():buffer.position()= 72,buffer.get()= - 106
  • 第四个get():buffer.position()= 73 ,buffer.get()= - 45

所以位置正确递增,但第72和第77之间的字节在某种程度上对缓冲区不可见?

Api明确指出:

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

我错过了什么?

1 个答案:

答案 0 :(得分:-1)

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