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

user1508893
  • 9,223
  • 14
  • 45
  • 57
  • 2
    http://stackoverflow.com/questions/1026761/how-to-convert-a-byte-array-to-its-numeric-value-java - look it up over here. – user Oct 19 '12 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? – jlordo Oct 19 '12 at 22:08
  • If they're both guaranteed to be 4 bytes, the leftmost bit is always the sign bit. – Louis Wasserman Oct 19 '12 at 22:15

1 Answers1

3

Why reinvent the wheel? Use ByteBuffer:

int a = ByteBuffer.wrap(byteArrayA).getInt();
int b = ByteBuffer.wrap(byteArrayB).getInt();
System.out.println(a == b);
Mirko Adari
  • 5,083
  • 1
  • 15
  • 23