简体   繁体   中英

Clamp BigInteger into a long

Is there a way to convert a Java BigInteger into a long , clamping it to the range of long ? I mean, if it's larger than Long.MAX_VALUE or smaller than Long.MIN_VALUE , use these edge values, otherwise use the exact value.

I ended up using this custom function:

public static long clampToLong(BigInteger val) {
    if (val.bitLength() <= 63) {
        return val.longValue();
    }
    return val.signum() == 1 ? Long.MAX_VALUE : Long.MIN_VALUE;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM