Initialization
suggest changeThe java.math.BigInteger class provides operations analogous to Java’s primitive integer operators and to the relevant methods from java.lang.Math. The java.math package is not imported automatically, so import java.math.BigInteger before using 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);
The following constructor translates the string representation of a BigInteger in the given radix.
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”.
BigInteger.TWO (value of “2”) is private through Java 8 and public since Java 9.