BigInteger
BigInteger
概述
在Java中,由CPU原生提供的整型最大范围是64位long型整数。使用long型整数可以直接通过CPU指令进行计算,速度非常快。
如果我们使用的整数范围超过了long型就只能用软件来模拟一个大整数。
java.math.BigInteger就是用来表示任意大小的整数。BigInteger内部用一个int[]数组来模拟一个非常大的整数。
- 优点:数值没有范围限制
- 缺点:相对Long运行速度较慢
/**
*
* @Description: 创建一个BigInteger实例
*
* @return void
* @param num
*
* @date: 2019年10月15日 下午4:12:31
*/
public static BigInteger createBigInteger(String num) {
return new BigInteger(num);
}
运算
两个BigInteger进行运算时,不可直接使用运算符,需要调用对应类方法进行计算
/**
*
* @Description: 两个BigInteger只能通过方法进行数值计算
*
* @return BigInteger
* @param bi1
* @param bi2
* @param calculateType
* @return
*
* @date: 2019年10月15日 下午4:18:59
*/
public static BigInteger calculate(BigInteger bi1,BigInteger bi2,String calculateType) {
switch (calculateType) {
case "+":
return bi1.add(bi2);
case "-":
return bi1.subtract(bi2);
case "*":
return bi1.multiply(bi2);
case "/":
return bi1.divide(bi2);
case "^":
return bi1.pow(bi2.intValueExact());
default:
return null;
}
}
类型转换
BigInteger和Integer、Long一样,也是不可变类,并且也继承自Number类。因为Number定义了转换为基本类型的几个方法:
-转换为byte:byteValue()
-转换为short:shortValue()
-转换为int:intValue()
-转换为long:longValue()
-转换为float:floatValue()
-转换为double:doubleValue()
TIPS:通过上述方法,可以把BigInteger转换成基本类型。如果BigInteger表示的范围超过了基本类型的范围,转换时将丢失高位信息,即结果不一定是准确的。
如果需要准确地转换成基本类型,可以使用
- intValueExact()
- longValueExact()等方法,在转换时如果超出范围,将直接抛出ArithmeticException异常。
/**
*
* @Description:
*
* @return long
* @param bi
* @return
*
* @date: 2019年10月15日 下午4:28:21
*/
public static long bigInteger2Long(BigInteger bi) {
// 数值超出long范围时,只返回低64位。此转换会丢失关于BigInteger值的总大小信息以及符号相反返回结果
// return bi.longValue();
// 此方法超出范围会抛出异常 java.lang.ArithmeticException: BigInteger out of long range
return bi.longValueExact();
}