BigInteger.bitLength() can return negative result

Dmitry Nadezhin Dmitry.Nadezhin at Sun.COM
Tue Oct 20 04:18:10 UTC 2009


I'm preparing a fix which restricts the range of BigInteger so that 
bitLength() always
return correct result.

I can't choose between two variants of range of valid BigInteger.

A) Two's complement range
[-2^Integer.MAX_VALUE, 2^Integer.MAX_VALUE-1]
This is exactly those numbers with bitLength() <= Integer.MAX_VALUE.

B) Symmetrical range
[-2^Integer.MAX_VALUE+1, 2^Integer.MAX_VALUE-1]

In variant A)
- x.neg() and x.abs() will throw ArithmeticException on minimum 
BigInteger value, because the exact result is out of range;
- bit operations or(), and(), xor(), andNot() will always return valid 
result.

In variant B)
- x.neg() and x.abs() will never throw ArithmeticException;
- and(), andNot(), xor() may throw ArithmeticException for certain 
arguments.

Which variant do you prefer ?

  -Dima

/
/>>>>/ d) All BigInteger constructors ensure that the bit length is no 
/>>>>/ larger than 2^31 - 1;
/>>>/
/>>>/ d) is arguably the most correct approach to address the problem.  
/>>>/ However, I think the practical consequences of this flaw are low.
/>>/ Nevertheless, may I use this unimportant flaw as a lesson of Java bug 
/>>/ fixing ?
/>>/
/>
>No fix for the bug has yet been offered.
>
>You're independently rediscovered a bug that has been in the platform 
>for about 12 years.
>
>-Joe




More information about the core-libs-dev mailing list