Search code examples
kotlinbiginteger

Convert BigInteger to ULong in Kotlin


Given a BigInteger in Kotlin that is in the range between 0 and 2^64, how can I convert this BigInteger to a ULong? Kotlin provides toULong() extension methods only for Byte/Short/Int/Long/Float/Double.


Solution

  • You can safely do bigint.toLong().toULong().

    The toLong() extension calls BigInteger.longValue(). The documentation for that says "if this BigInteger is too big to fit in a long, only the low-order 64 bits are returned".

    Then the Long.toULong() extension is documented as "The resulting ULong value has the same binary representation as this Long value."

    So with those two together, we can see that toLong().toULong() will preserve all 64 bits of a BigInteger between 0 and 2^64-1.