Initialization

suggest change

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:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


BigInteger:
* Initialization

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
58 BigInteger
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap