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 ByteBuffers also have the right values (according to the debugger). What is the problem here?
The
compareTocompares the remaining bytes of the buffers. Therefore you must firstflip()both buffers before the comparison.Without the
flipyou will compare the bytes[2..3] in each buffer. Because you did not write those bytes, they all will be zero. With theflipyou will compare the bytes[0..1] which contains the data you have written from the arrays.