比较 ByteBuffer 中的字节
我在 Java 中有一个大小为 4 的 byte
数组,我试图将其前两个字节放入 ByteBuffer
中。
我是这样做的:
byte[] array = new byte[4];
ByteBuffer buff = ByteBuffer.allocate(2);
buff.put(array, 0, 2);
我的代码有什么问题?
编辑:
byte[] currRecord = new byte[4];
byte[] leftRecord = new byte[4];
// Code that populates the records
ByteBuffer currKey = ByteBuffer.allocate(2);
currKey = currKey.put(currRecord, 0, 2);
ByteBuffer leftKey = ByteBuffer.allocate(2);
leftKey = leftKey.put(leftRecord, 0, 2);
然后我尝试比较两个 ByteBuffers ,如下所示:
if (currKey.compareTo(leftKey) >= 0)
return;
我的比较总是错误的。调试时,我非常确定 currRecord 和 leftRecord 具有正确的值。 ByteBuffer 也具有正确的值(根据调试器)。这里有什么问题呢?
I have a byte
array in Java of size 4, which I am trying to put the first two bytes of into ByteBuffer
.
Here is how I am doing it:
byte[] array = new byte[4];
ByteBuffer buff = ByteBuffer.allocate(2);
buff.put(array, 0, 2);
What's wrong with my code?
EDIT:
byte[] currRecord = new byte[4];
byte[] leftRecord = new byte[4];
// Code that populates the records
ByteBuffer currKey = ByteBuffer.allocate(2);
currKey = currKey.put(currRecord, 0, 2);
ByteBuffer leftKey = ByteBuffer.allocate(2);
leftKey = leftKey.put(leftRecord, 0, 2);
Then I am trying to compare both ByteBuffers
as follows:
if (currKey.compareTo(leftKey) >= 0)
return;
My comparison is always wrong. When debugging, I am pretty sure currRecord
and leftRecord
have the right values. The ByteBuffer
s also have the right values (according to the debugger). What is the problem here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
compareTo
比较缓冲区的剩余字节。因此,在比较之前,您必须首先flip()
两个缓冲区。如果没有
flip
,您将比较每个缓冲区中的字节[2..3]。因为您没有写入这些字节,所以它们都将为零。使用flip
,您将比较包含从数组写入的数据的字节[0..1]。The
compareTo
compares the remaining bytes of the buffers. Therefore you must firstflip()
both buffers before the comparison.Without the
flip
you will compare the bytes[2..3] in each buffer. Because you did not write those bytes, they all will be zero. With theflip
you will compare the bytes[0..1] which contains the data you have written from the arrays.您还没有说出您要寻找的结果。您发布的代码对我来说效果很好
//outputs "equal"
您是否期望这不相等?如果是这样,我不明白为什么。您的代码中没有任何内容明确表示这些不相等。
注意 - 在两个缓冲区上调用
flip()
仍会产生“equal”。You still haven't said what results you're looking for. The code you have posted worked fine for me
//outputs "equal"
Were you expecting this to not be equal? If so, I don't see why. There's nothing in your code that would explicitly say these aren't equal.
Note - Calling
flip()
on both buffers will still produce "equal".