Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpret a negative number as unsigned with BigInteger

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.

like image 371
One Two Three Avatar asked Nov 28 '22 09:11

One Two Three


1 Answers

Try using the constructor

public BigInteger(int signum, byte[] magnitude)

The first parameter should be set to 1 to specify you want to create a positive number. The byte array is the number you are parsing in BIG ENDIAN ORDER. It should be interpreted as an unsigned number if you set the first parameter to 1. The only trick is getting your number into a byte array, but that shouldn't bee too difficult.

EDIT: Looks like you have to do some manual bit arithmetic here. If I understand your problem correctly, you need to interpret a String as a Long and then interpret that long as unsigned and store that in the BigInteger class. I would do this.

public BigInteger getValue(String numberString)
{
   Long longValue = Long.valueOf(numberString);
   byte [] numberAsArray = new byte[8];  
   for(int i = 0; i < 8; i++)
   {  
      numberAsArray[7 - i] = (byte)((longValue >>> (i * 8)) & 0xFF);
   }
   return new BigInteger(1, numberAsArray);
}  
like image 177
Akron Avatar answered Dec 15 '22 06:12

Akron