BigInteger、BigDecimal类的使用详解
我们都知道在java里边long算是存储长度比较大的了,但是如果有很大的数我们应该怎么处理呢,不用怕,java还为我们准备了一个BigInteger的类,那么这个类到底能存储多大的数呢,这个一时还真不好想,要取决于你计算机的内存大小,意味着我们的内存越大,这个类存储的位数就越大。接下来我们来看看BigInteger这个类。
BigInteger继承了Number类并且实现了Serializable , Comparable < BigInteger >接口
首先来看他的构造函数
这个类与之对应的还有三个常量,我们来看下
接下来我们说下他常用的构造函数
比较常用的就是用字符串来直接传入
BigInteger bigInteger = new BigInteger("999999999999999999");
比较常用的成员方法有如下:
BigInteger abs() 返回大整数的绝对值
BigInteger add(BigInteger val) 返回两个大整数的和
BigInteger and(BigInteger val) 返回两个大整数的按位与的结果
BigInteger andNot(BigInteger val) 返回两个大整数与非的结果
BigInteger divide(BigInteger val) 返回两个大整数的商
double doubleValue() 返回大整数的double类型的值
float floatValue() 返回大整数的float类型的值
BigInteger gcd(BigInteger val) 返回大整数的最大公约数
int intValue() 返回大整数的整型值
long longValue() 返回大整数的long型值
BigInteger max(BigInteger val) 返回两个大整数的最大者
BigInteger min(BigInteger val) 返回两个大整数的最小者
BigInteger mod(BigInteger val) 用当前大整数对val求模
BigInteger multiply(BigInteger val) 返回两个大整数的积
BigInteger negate() 返回当前大整数的相反数
BigInteger not() 返回当前大整数的非
BigInteger or(BigInteger val) 返回两个大整数的按位或
BigInteger pow(int exponent) 返回当前大整数的exponent次方
BigInteger remainder(BigInteger val) 返回当前大整数除以val的余数
BigInteger leftShift(int n) 将当前大整数左移n位后返回
BigInteger rightShift(int n) 将当前大整数右移n位后返回
BigInteger subtract(BigInteger val)返回两个大整数相减的结果
byte[] toByteArray(BigInteger val)将大整数转换成二进制反码保存在byte数组中
String toString() 将当前大整数转换成十进制的字符串形式
BigInteger xor(BigInteger val) 返回两个大整数的异或
我们来看几个测试
public static void main(String[] args) {
BigInteger b1 = new BigInteger("999999999999999999999");
BigInteger b2 = new BigInteger("888888888888888888888");
//加法
System.out.println(b1.subtract(b2));
//减法
System.out.println(b1.add(b2));
//乘法
System.out.println(b1.multiply(b2));
//除法
System.out.println(b1.divide(b2));
//取余
System.out.println(b1.remainder(b2));
//除并取余
BigInteger[] bbs = b1.divideAndRemainder(b2);
System.out.println(bbs[0]+"--"+bbs[1]);
}
程序的运行结果如下:
111111111111111111111
1888888888888888888887
888888888888888888887111111111111111111112
1
111111111111111111111
1--111111111111111111111
接下来我带大家看下BigInteger底层的源码
这个this是什么东西呢,我们继续往下看
/**
* Translates the String representation of a BigInteger in the
* specified radix into a BigInteger. The String representation
* consists of an optional minus or plus sign followed by a
* sequence of one or more digits in the specified radix. The
* character-to-digit mapping is provided by {@code
* Character.digit}. The String may not contain any extraneous
* characters (whitespace, for example).
*
* @param val String representation of BigInteger.
* @param radix radix to be used in interpreting {@code val}.
* @throws NumberFormatException {@code val} is not a valid representation
* of a BigInteger in the specified radix, or {@code radix} is
* outside the range from {@link Character#MIN_RADIX} to
* {@link Character#MAX_RADIX}, inclusive.
* @see Character#digit
*/
public BigInteger(String val, int radix) { //首先这里有一个基数因子 是指当前是多少进制的
int cursor = 0, numDigits;
final int len = val.length(); //这个地方会获取到当前传入字符串的总长度
//这里有两个常量 MIN_RADIX = 2 , MAX_RADIX = 36
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
throw new NumberFormatException("Radix out of range");
if (len == 0)
throw new NumberFormatException("Zero length BigInteger");
// Check for at most one leading sign
//这里会检测传入的字符串是否是纯数字
int sign = 1;
int index1 = val.lastIndexOf('-');
int index2 = val.lastIndexOf('+');
if (index1 >= 0) {
if (index1 != 0 || index2 >= 0) {
throw new NumberFormatException("Illegal embedded sign character");
}
sign = -1;
cursor = 1;
} else if (index2 >= 0) {
if (index2 != 0) {
throw new NumberFormatException("Illegal embedded sign character");
}
cursor = 1;
}
if (cursor == len)
throw new NumberFormatException("Zero length BigInteger");
// Skip leading zeros and compute number of digits in magnitude
while (cursor < len &&
Character.digit(val.charAt(cursor), radix) == 0) {
cursor++;
}
if (cursor == len) {
signum = 0;
mag = ZERO.mag;
return;
}
numDigits = len - cursor;
signum = sign;
// Pre-allocate array of expected size. May be too large but can
// never be too small. Typically exact.
long numBits = ((numDigits * bitsPerDigit[radix]) >>> 10) + 1;
if (numBits + 31 >= (1L << 32)) {
reportOverflow();
}
int numWords = (int) (numBits + 31) >>> 5;
int[] magnitude = new int[numWords];
// Process first (potentially short) digit group
int firstGroupLen = numDigits % digitsPerInt[radix];
if (firstGroupLen == 0)
firstGroupLen = digitsPerInt[radix];
String group = val.substring(cursor, cursor += firstGroupLen);
magnitude[numWords - 1] = Integer.parseInt(group, radix);
if (magnitude[numWords - 1] < 0)
throw new NumberFormatException("Illegal digit");
// Process remaining digit groups
int superRadix = intRadix[radix];
int groupVal = 0;
while (cursor < len) {
group = val.substring(cursor, cursor += digitsPerInt[radix]);
groupVal = Integer.parseInt(group, radix);
if (groupVal < 0)
throw new NumberFormatException("Illegal digit");
destructiveMulAdd(magnitude, superRadix, groupVal);
}
// Required for cases where the array was overallocated.
mag = trustedStripLeadingZeroInts(magnitude);
if (mag.length >= MAX_MAG_LENGTH) {
checkRange();
}
}
看了以上的代码,相信你对BigInteger大概已经有了一个新的认识。
以上内容部分来自网络,与BigInteger对应的还有一个BigDecimal,可以存小数,与BigInteger的用法一模一样,有问题可以在下面评论,技术问题可以私聊我。
BigInteger、BigDecimal类的使用详解的更多相关文章
- 【转】UML类图与类的关系详解
UML类图与类的关系详解 2011-04-21 来源:网络 在画类图的时候,理清类和类之间的关系是重点.类的关系有泛化(Generalization).实现(Realization).依赖(D ...
- String类的构造方法详解
package StringDemo; //String类的构造方法详解 //方法一:String(); //方法二:String(byte[] bytes) //方法三:String (byte[] ...
- [转]c++类的构造函数详解
c++构造函数的知识在各种c++教材上已有介绍,不过初学者往往不太注意观察和总结其中各种构造函数的特点和用法,故在此我根据自己的c++编程经验总结了一下c++中各种构造函数的特点,并附上例子,希望对初 ...
- Scala 深入浅出实战经典 第63讲:Scala中隐式类代码实战详解
王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-87讲)完整视频.PPT.代码下载:百度云盘:http://pan.baidu.com/s/1c0noOt6 ...
- UML类图与类的关系详解
摘自:http://www.uml.org.cn/oobject/201104212.asp UML类图与类的关系详解 2011-04-21 来源:网络 在画类图的时候,理清类和类之间的关系是重点.类 ...
- phpcms加载系统类与加载应用类之区别详解
<?php 1. 加载系统类方法load_sys_class($classname, $path = ''", $initialize = 1)系统类文件所在的文件路径:/phpcms ...
- c++类的构造函数详解
c++类的构造函数详解 一. 构造函数是干什么的 class Counter{ public: // 类Counter的构造函数 // 特点:以类名作为函数名,无返回类 ...
- 对python3中pathlib库的Path类的使用详解
原文连接 https://www.jb51.net/article/148789.htm 1.调用库 ? 1 from pathlib import 2.创建Path对象 ? 1 2 3 4 5 ...
- String类内存空间详解
java.lang.String类内存问题详解 字符串理解的难点在于其在堆内存空间上的特殊性,字符串String对象在堆内存上有两种空间: 字符串池(String pool):特殊的堆内存,专门存放S ...
随机推荐
- Python学习-while循环语句
Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务.即重复性的做一件事情 语法形式如下: while 判断条件: 条件满足执行语句…… ...
- 每日命令:(11)nl
nl命令在linux系统中用来计算文件中行号.nl 可以将输出的文件内容自动的加上行号!其默认的结果与 cat -n 有点不太一样, nl 可以将行号做比较多的显示设计,包括位数与是否自动补齐 0 等 ...
- 阿里云创建CentOS系统设置
1 首先设置你购买的云盘配置,例如cpu,内存,磁盘类型.容量,网络类型等 2.阿里云可以使用浏览器进行远程shell连接 首先需要输入远程密码,第一次连接的时候会提示 一定要牢记 输入密码后进入sh ...
- convert images to a video (Ubuntu)
use =avconv= package e.g. to convert images (v_1.png, v_2.png ...) to 'velocity.mp4' >>> a ...
- JavaSE 学习笔记之IO流(二十二)
IO流:用于处理设备上数据. 流:可以理解数据的流动,就是一个数据流.IO流最终要以对象来体现,对象都存在IO包中. 流也进行分类: 1:输入流(读)和输出流(写). 2:因为处理的数据不同,分为字节 ...
- redis+spring
1. 在配置文件中添加 注解 <cache:annotation-driven cache-manager="cacheManager" key-generator=&quo ...
- 最小生成树+BFS J - Borg Maze
The Borg is an immensely powerful race of enhanced humanoids from the delta quadrant of the galaxy. ...
- Spring MVC中@RequestMapping注解使用技巧(转)
@RequestMapping是Spring Web应用程序中最常被用到的注解之一.这个注解会将HTTP请求映射到MVC和REST控制器的处理方法上. 在这篇文章中,你将会看到@RequestMapp ...
- Nginx 重写规则指南
作者:运维生存时间 - 默北 链接:www.ttlsa.com/nginx/nginx-rewriting-rules-guide/ 当运维遇到要重写情况时,往往是要程序员把重写规则写好后,发给你,你 ...
- cisco路由器上的DHCP
一.实验拓扑 二.具体配置 Router(config)#do sh run Building configuration... Current configuration : 604 bytes ...