2

I have two byte-arrays (in Java) representing two (possibly negative) numbers.

How do I compare them (ie., finding out which one is smaller/greater)?

Currently, I just compare them by resurrecting them into two java's int and then doing the comparison. But that'd give the wrong result in cases where one of the byte-array represents a negative number and the other positive.It's impossible to tell whether the left-most bit is the sign or just part of the number, right?

Thanks

3
  • 2
    stackoverflow.com/questions/1026761/… - look it up over here. Commented Oct 19, 2012 at 21:30
  • Are your bytes ordered from most significant to least or the other way? If from most to least: Isn't the left-most bit the sign in the first byte and just part of the number in all following bytes? Do you have a constant number of bytes, or do they vary? Commented Oct 19, 2012 at 22:08
  • If they're both guaranteed to be 4 bytes, the leftmost bit is always the sign bit. Commented Oct 19, 2012 at 22:15

1 Answer 1

3

Why reinvent the wheel? Use ByteBuffer:

int a = ByteBuffer.wrap(byteArrayA).getInt();
int b = ByteBuffer.wrap(byteArrayB).getInt();
System.out.println(a == b);
Sign up to request clarification or add additional context in comments.

1 Comment

You can specify order with ByteBuffer. order(ByteOrder.BIG_ENDIAN)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.