Appearance
BigInteger
In Java, the maximum range of integers provided natively by the CPU is a 64-bit long
integer. Using long
integers can be calculated directly through CPU instructions, which is very fast.
What if the range of integers we use exceeds long
type? At this time, you can only use software to simulate a large integer. java.math.BigInteger
is used to represent integers of any size. BigInteger
internally uses an int[]
array to simulate a very large integer:
java
BigInteger bi = new BigInteger("1234567890");
System.out.println(bi.pow(5)); // 2867971860299718107233761438093672048294900000
When performing operations on BigInteger
, you can only use instance methods, for example, addition:
java
BigInteger i1 = new BigInteger("1234567890");
BigInteger i2 = new BigInteger("12345678901234567890");
BigInteger sum = i1.add(i2); // 12345678902469135780
Compared with long
integer operations, BigInteger
does not have range restrictions, but the disadvantage is that it is slower.
You can also convert BigInteger
to long
type:
java
BigInteger i = new BigInteger("123456789000");
System.out.println(i.longValue()); // 123456789000
System.out.println(i.multiply(i).longValueExact()); // java.lang.ArithmeticException: BigInteger out of long range
When using the longValueExact()
method, if it exceeds the range of the long
type, ArithmeticException
will be thrown.
BigInteger
, like Integer
and Long
, is also an immutable class and also inherits from the Number
class. Because Number
defines several methods for conversion to basic types:
- Convert to
byte
:byteValue()
- Convert to
short
:shortValue()
- Convert to
int
:intValue()
- Convert to
long
:longValue()
- Convert to
float
:floatValue()
- Convert to
double
:doubleValue()
Therefore, through the above method, BigInteger
can be converted into a basic type. If the range represented by BigInteger
exceeds the range of the basic type, the high-order information will be lost during conversion, that is, the result may not be accurate.
If you need to accurately convert to a basic type, you can use intValueExact()
, longValueExact()
and other methods. If it goes out of range during conversion, ArithmeticException
will be thrown directly.
If the value of BigInteger
even exceeds the maximum range of float
(3.4x10 38 ), what is the returned float?
java
// BigInteger to float
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
BigInteger n = new BigInteger("999999").pow(99);
float f = n.floatValue();
System.out.println(f); // Infinity
}
}
Summary
BigInteger
is used to represent integers of any size;
BigInteger
is an immutable class and inherits from Number
;
When converting BigInteger
into a basic type, you can use methods such as longValueExact()
to ensure accurate results.