如何处理大于机器代表号的数字? [英] How to handle numbers bigger than machine representative number?

查看:92
本文介绍了如何处理大于机器代表号的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设现在我正在为我的数据库分配ID号,数据库很大(超过机器代表号的项目)。

Assuming now I'm assigning ID number to my database, the database is huge(items more than machine representative number).

我正在使用Java,I知道Java中最大的数据类型是long int(64位)。我怎么能处理比这更大的数字?

I'm using Java, I know the biggest data type in Java is long int(64 bit). How could I deal with numbers bigger than that?

我的一个解决方案总是将数字转换成字符串,这将导致开销,我仍然不知道如何累积要转换为字符串的数字(大于MAX_VALUE)。

One of my solutions is always converting numbers to strings, which will cause the overhead and I still don't figure out how to accumulate the number(bigger than MAX_VALUE) that is meant to converted to strings.

推荐答案

使用 java.math.BigInteger

BigInteger a = new BigInteger("123456789012345678901234567890");
BigInteger b = new BigInteger("314159265");
BigInteger c = a.add(b);
System.out.println(c);

注意(1) BigInteger s是不可变的(2)你必须使用方法添加减去等,而不是 + - 等。

Note (1) BigIntegers are immutable and (2) you have to use the methods add, subtract, etc. rather than +, -, etc.

此外, BigInteger (及其浮点模拟, BigDecimal )比原始类型慢得多。 BigInteger 适用于大多数情况,但如果可能,请在性能敏感代码中避免使用它。

Also, BigInteger (and its floating-point analog, BigDecimal) is much lower slower than primitive types. BigInteger is fine for most cases, but avoid it if possible in performance sensitive code.

这篇关于如何处理大于机器代表号的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆