Is it possible to parse a negative number into an unsigned value with Java's BigInteger
?
So for instance, I'd to interpret -1
as FFFFFFFFFFFFFFFF
.
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.
You could do something as this:
// 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));
}
But this would implicitly mean that you are working with BigIntegers in the 0 - 2^64-1 range.
Or, more general:
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;
}