比较ByteBuffer中的字节

时间:2011-11-01 22:01:15

标签: java arrays bytebuffer

我有一个大小为4的Java 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;

我的比较总是错的。调试时,我非常确定currRecordleftRecord具有正确的值。 ByteBuffer也具有正确的值(根据调试器)。这有什么问题?

2 个答案:

答案 0 :(得分:1)

compareTo比较缓冲区的剩余字节。因此,在比较之前,您必须首先flip()两个缓冲区。

如果没有flip,您将比较每个缓冲区中的字节[2..3]。因为你没有写那些字节,所以它们都是零。使用flip,您将比较包含您从数组中写入的数据的字节[0..1]。

答案 1 :(得分:0)

你还没有说出你想要的结果。您发布的代码对我来说很好

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);

if (currKey.compareTo(leftKey) == 0)
    System.out.println("equal");
else
    System.out.println("not equal");

//输出“相等”

您是否期望相等?如果是这样,我不明白为什么。您的代码中没有任何内容可以明确说明这些不相等

注意 - 在两个缓冲区上调用flip()仍然会产生“相等”。