datv
datv

Reputation: 617

How to Compare two BigInteger variables as unsigned?

I have two BigInteger variables whose values are initialized from 8 byte arrays:

maxOne: ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
midOne: 8000:8000:8000:8000:8000:8000:8000:8000

I would like to use a BigInteger comparison method that would return that maxOne is greater than midOne.

However, I keep getting the opposite. i.e. midOne is greater than maxOne.

Internally, I could see that they are stored as:

maxOne:

mag[0]: 1
signum: -1

midOne

mag[0]: 7FFF7FFF
mag[1]: 7FFF7FFF
mag[2]: 7FFF7FFF
mag[3]: 7FFF8000
signum: -1

I would think a "larger absolute" value is lesser than a "smaller absolute" value when both have signum=-1 (e.g. -3 is lesser than -1).

But for some reason, maxOne.compareTo(midOne) returns -1.

When examining their BigInteger.doubleValue(), I see that

maxOne = -1.0
midOne = -1.7013858727242528 E38

Even if compareTo() were to use the doubleValue() to do the compare, maxOne > midOne.

So, why is the comparison returning the opposite?

Either way, I am interested comparing them as two unsigned integers. Is there a way to accomplish that?

Upvotes: 3

Views: 178

Answers (1)

user2496748
user2496748

Reputation: 65

I suggest to put a zero byte at the most significant place. So that no sign bit can creep in when creating the BigInteger.

Upvotes: 3

Related Questions