Java-串联的ByteBuffer上的CRC32.update() [英] Java - CRC32.update() on concatenated ByteBuffer
问题描述
我具有以下功能:
byte[] test1 = {1,2,3,4};
byte[] test2 = {5,6,7,8};
ByteBuffer bbtest1 = ByteBuffer.wrap(test1).order(ByteOrder.LITTLE_ENDIAN);
ByteBuffer bbtest2= ByteBuffer.wrap(test2).order(ByteOrder.LITTLE_ENDIAN);
ByteBuffer contents = ByteBuffer.allocate(bbtest1.limit() + bbtest2.limit());
contents.put(bbtest1);
contents.put(bbtest2);
CRC32 checksum = new CRC32();
checksum.update(contents);
System.out.println(checksum.getValue());
无论我为字节数组分配了什么值,当通过以下方式连接时,getValue()始终返回0 byteBuffers。根据 byte [] test2 = {5,6,7,8};
行,则getValue ()实际上返回一个有效值。
No matter what values I assign my byte arrays, getValue() always returns 0 when I have concatenated by byteBuffers. According to this thread, this is a valid way of concatenating byteBuffers. If I only call put() on a single byteBuffer (for example if I comment out the line byte[] test2 = {5,6,7,8};
then getValue() actually returns a valid value.
这是ByteBuffer的连接方式的问题,update(ByteBuffer)在已连接的ByteBuffer上执行的问题,或者也许是其他原因吗?
Is this an issue with the way the ByteBuffers are concatenated, update(ByteBuffer) performs on concatenated ByteBuffers, or maybe something else altogether?
推荐答案
您对 put
的调用已将ByteBuffer的位置提高到
Your calls to put
have advanced the position of the ByteBuffer to the point that there is no byte left to read from it for CRC32.update()
.
如果仅放入两个字节缓冲区之一,那么仍然会有4个字节要读取CRC校验和(所有4个字节的值均为0)。
If you only put one of the two byte buffers, then there will still be 4 bytes to read for the CRC checksum (all 4 have the value 0).
您需要重置在调用 checksum.update(contents)
之前,字节缓冲区的位置为零。可以使用 rewind
或翻转
:
You need to reset the position of your bytebuffer to zero before calling checksum.update(contents)
. You can use rewind
or flip
for that:
contents.rewind();
或
contents.flip();
翻转与 rewind()
相同,但它还会将ByteBuffer的限制
设置为翻转前的位置
,因此,如果您首先构造了ByteBuffer的内容然后要从中读取, flip()
更正确,因为您不必冒着从ByteBuffer的某些部分读取的风险
Flip does the same as rewind()
, but additionally it sets the limit
of the ByteBuffer to the position
it had before flipping, so if you first constructed the content of the ByteBuffer and then want to read from it, flip()
is more correct, as you don't run the risk of reading from parts of the ByteBuffer that you didn't yet write into.
EJP的答案很有见地,因为他指出您根本不需要连接字节缓冲区。
EJP's answer is insightful, as he points out that you don't need to concatenate byte buffers at all.
您也可以执行以下操作之一:
You can alternatively do one of:
- 使用单个ByteBuffer更新CRC32
- 使用
ByteBuffer.put(byte [])
直接放置test1
和<$ c $目录中的c> test2
字节数组 ByteBuffer - 完全跳过ByteBuffer并调用
CRC32.update(byte [])
依次按test1
和test2
。
- update the CRC32 with the individual ByteBuffers
- use
ByteBuffer.put(byte[])
to directly put thetest1
andtest2
byte arrays in thecontents
ByteBuffer - skip ByteBuffers altogether and call
CRC32.update(byte[])
withtest1
andtest2
in sequence.
这篇关于Java-串联的ByteBuffer上的CRC32.update()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!