You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中如何将0至2^64范围的BigInteger转换为ULong?

在Kotlin中将0到2^64范围的BigInteger转换为ULong

Kotlin标准库只给Byte、Short、Int、Long、Float、Double这几种基础类型提供了toULong()扩展方法,BigInteger并没有现成的转换方法,下面是可行的解决办法:

方法1:分区间处理(适配0到2^64-1的BigInteger)

ULong的有效取值范围是0到2^64 - 1,如果你的BigInteger落在这个区间内,可以这样转:

  • 当数值 ≤ Long.MAX_VALUE(也就是2^63 -1)时,直接用longValueExact()拿到Long值再转ULong:
    val bigInt = BigInteger("123456789")
    val uLongVal = bigInt.longValueExact().toULong()
    
  • 当数值 > Long.MAX_VALUE且 ≤ ULong.MAX_VALUE时,用longValue()获取低64位的有符号Long值,再转ULong就行——因为无符号的ULong会正确解析这个补码对应的无符号值:
    val bigInt = BigInteger("9223372036854775808") // 2^63,超过Long的最大值
    val uLongVal = bigInt.longValue().toULong()
    

方法2:封装通用扩展函数(带范围校验)

可以写个扩展函数自动处理不同区间,还能校验数值是否超出ULong的可表示范围:

fun BigInteger.toULong(): ULong {
    require(this >= BigInteger.ZERO) { "BigInteger必须是非负数" }
    require(this <= BigInteger.valueOf(ULong.MAX_VALUE.toLong()).add(BigInteger.ONE)) { 
        "BigInteger超出了ULong的最大值(2^64 - 1)" 
    }
    return if (this <= BigInteger.valueOf(Long.MAX_VALUE)) {
        this.longValueExact().toULong()
    } else {
        this.longValue().toULong()
    }
}

注意:如果BigInteger等于2^64,转ULong会溢出,因为ULong的最大值是2^64 -1。这种情况你得自己处理溢出逻辑,比如返回ULong.MIN_VALUE或者抛自定义异常。

内容的提问来源于stack exchange,提问作者Danilo Bargen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 08:02:51