用BigInteger解释一个无符号负数 [英] Interpret a negative number as unsigned with BigInteger

查看:423
本文介绍了用BigInteger解释一个无符号负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用Java的BigInteger将负数解析为无符号值?

Is it possible to parse a negative number into an unsigned value with Java's BigInteger?

例如,我将-1解释为FFFFFFFFFFFFFFFF.

推荐答案

如果要考虑二进制补码,则必须指定工作位长度. Java long有64位,但是BigInteger没有边界.

If you are thinking of a two's complement, you must specify a working bit length. A Java long has 64 bits, but a BigInteger is not bounded.

您可以这样做:

// Two's complement reference: 2^n . 
// In this case, 2^64 (so as to emulate a unsigned long)
private static final BigInteger TWO_COMPL_REF = BigInteger.ONE.shiftLeft(64);

public static BigInteger parseBigIntegerPositive(String num) {
    BigInteger b = new BigInteger(num);
    if (b.compareTo(BigInteger.ZERO) < 0)
        b = b.add(TWO_COMPL_REF);
    return b;
}

public static void main(String[] args) {
    System.out.println(parseBigIntegerPositive("-1").toString(16));
}

但这暗含着您正在使用0-2 ^ 64-1范围内的BigIntegers.

But this would implicitly mean that you are working with BigIntegers in the 0 - 2^64-1 range.

或更笼统:

public static BigInteger parseBigIntegerPositive(String num,int bitlen) {
    BigInteger b = new BigInteger(num);
    if (b.compareTo(BigInteger.ZERO) < 0)
        b = b.add(BigInteger.ONE.shiftLeft(bitlen));
    return b;
}

要使其更加防呆,可以添加一些检查,例如

To make it more fooproof, you could add some checks, eg

public static BigInteger parseBigIntegerPositive(String num, int bitlen) {
    if (bitlen < 1)
        throw new RuntimeException("Bad bit length:" + bitlen);
    BigInteger bref = BigInteger.ONE.shiftLeft(bitlen);
    BigInteger b = new BigInteger(num);
    if (b.compareTo(BigInteger.ZERO) < 0)
        b = b.add(bref);
    if (b.compareTo(bref) >= 0 || b.compareTo(BigInteger.ZERO) < 0 )
        throw new RuntimeException("Out of range: " + num);
    return b;
}

这篇关于用BigInteger解释一个无符号负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆