
在Java中由CPU原生提供的整型最大范围是64位long型整数。使用long型整数可以直接通过CPU指令进行计算速度非常快。如果我们使用的整数范围超过了long型怎么办这个时候就只能用软件来模拟一个大整数。java.math.BigInteger就是用来表示任意大小的整数。BigInteger内部用一个int[]数组来模拟一个非常大的整数BigInteger bi new BigInteger(1234567890); System.out.println(bi.pow(5)); // 2867971860299718107233761438093672048294900000对BigInteger做运算的时候只能使用实例方法例如加法运算BigInteger i1 new BigInteger(1234567890); BigInteger i2 new BigInteger(12345678901234567890); BigInteger sum i1.add(i2); // 12345678902469135780和long型整数运算比BigInteger不会有范围限制但缺点是速度比较慢。也可以把BigInteger转换成long型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使用longValueExact()方法时如果超出了long型的范围会抛出ArithmeticException。BigInteger和Integer、Long一样也是不可变类并且也继承自Number类。因为Number定义了转换为基本类型的几个方法转换为bytebyteValue()转换为shortshortValue()转换为intintValue()转换为longlongValue()转换为floatfloatValue()转换为doubledoubleValue()因此通过上述方法可以把BigInteger转换成基本类型。如果BigInteger表示的范围超过了基本类型的范围转换时将丢失高位信息即结果不一定是准确的。如果需要准确地转换成基本类型可以使用intValueExact()、longValueExact()等方法在转换时如果超出范围将直接抛出ArithmeticException异常。如果BigInteger的值甚至超过了float的最大范围3.4x1038那么返回的float是什么呢// 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 } }喜欢这个系列的同学可以关注我爆肝一个月Python 从入门到精通