-4

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?

A.H.
  • 63,967
  • 15
  • 92
  • 126
darksky
  • 20,411
  • 61
  • 165
  • 254
  • 1
    The code you posted will work fine (although there is nothing interesting in `array`). Post your real code. – Mike Daniels Nov 01 '11 at 22:03
  • 1
    Q: "What's wrong with my code?" A: "It's wrong!?!" Tell us what is happening and what you're expecting to happen. The code is simple enough that if you sit down and try to explain to us what is the problem, then you will most likely figure out the solution (and you may not need to post an SO question). – Kiril Nov 01 '11 at 22:05
  • 1
    To echo Link -- what makes you think something is wrong with your code? What is it doing (or not doing) that is different from what you expect? – Ted Hopp Nov 01 '11 at 22:07
  • Well I thought it was the problem and you just pointed out it was right! See the edit. – darksky Nov 01 '11 at 22:10

2 Answers2

1

The compareTo compares the remaining bytes of the buffers. Therefore you must first flip() 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 the flip you will compare the bytes[0..1] which contains the data you have written from the arrays.

A.H.
  • 63,967
  • 15
  • 92
  • 126
0

You still haven't said what results you're looking for. The code you have posted worked fine for me

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

//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".

Nick Rolando
  • 25,879
  • 13
  • 79
  • 119