Optimise longValueExact(BigInteger n) in BigIntegerUtil
mpnd opened this issue · comments
mpnd commented
Given a value n
of type BigInteger
, longValueExact()
computes the exact long value of n
, that is n > Long.MaxValue
or n < Long.MinValue
result in ArithmeticException
. Currently, this conversion is calculated by comparing n
to BigInteger
of Long.MaxValue
and Long.MinValue
. Is there a solution which doesn’t involve comparison of two BigIntegers
?
Wilko Henecka commented
If you assume that long
is always a 64 bit integer in two's complement format, than you could test:
if (n>=0 and n.bitlength()<64) or (n<0 and (n-1).bitLength()<64) then
return n.longValue()
else
throw Exception
But is comparing two BigIntegers such a big deal?