Java Language Initialization


Example

The java.math.BigInteger class provides operations analogues to all of Java's primitive integer operators and for all relevant methods from java.lang.Math. As the java.math package is not automatically made available you may have to import java.math.BigInteger before you can use the simple class name.

To convert long or int values to BigInteger use:

long longValue = Long.MAX_VALUE;
BigInteger valueFromLong = BigInteger.valueOf(longValue); 

or, for integers:

int intValue = Integer.MIN_VALUE; // negative
BigInteger valueFromInt = BigInteger.valueOf(intValue);

which will widen the intValue integer to long, using sign bit extension for negative values, so that negative values will stay negative.


To convert a numeric String to BigInteger use:

String decimalString = "-1";
BigInteger valueFromDecimalString = new BigInteger(decimalString);

Following constructor is used to translate the String representation of a BigInteger in the specified radix into a BigInteger.

String binaryString = "10";
int binaryRadix = 2;
BigInteger valueFromBinaryString = new BigInteger(binaryString , binaryRadix);

Java also supports direct conversion of bytes to an instance of BigInteger. Currently only signed and unsigned big endian encoding may be used:

byte[] bytes = new byte[] { (byte) 0x80 }; 
BigInteger valueFromBytes = new BigInteger(bytes);

This will generate a BigInteger instance with value -128 as the first bit is interpreted as the sign bit.

byte[] unsignedBytes = new byte[] { (byte) 0x80 };
int sign = 1; // positive
BigInteger valueFromUnsignedBytes = new BigInteger(sign, unsignedBytes);

This will generate a BigInteger instance with value 128 as the bytes are interpreted as unsigned number, and the sign is explicitly set to 1, a positive number.


There are predefined constants for common values:

  • BigInteger.ZERO — value of "0".
  • BigInteger.ONE — value of "1".
  • BigInteger.TEN — value of "10".

There's also BigInteger.TWO (value of "2"), but you can't use it in your code because it's private.