java BigInteger 如何存储其数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5878603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:15:09  来源:igfitidea点击:

How does BigInteger store its data?

javabiginteger

提问by Jon Egeland

I've been searching around for quite a while, and I've found almost nothing on how BigIntegeractually holds its numbers. Are they an array of chars? Something else? And how is data converted to/from BigInteger?

我已经搜索了很长一段时间,但几乎没有发现关于BigInteger实际如何保存其数字的任何内容。它们是字符数组吗?还有什么?以及数据如何转换为/从BigInteger

From what I've found, I am assuming that all of arbitrary precision classes, like BigIntegerand BigDecimal, hold data as a character array. Is this how it actually works? Or is it just people's guess?

根据我的发现,我假设所有的任意精度类,比如BigIntegerBigDecimal,都将数据作为字符数组保存。这是它实际工作的方式吗?还是只是人们的猜测?

I'm asking because I have been working on my own implementation of something like BigInteger, but I can't figure out how to hold numbers larger than Long.MAX_VALUE(I don't remember the actual number).

我问是因为我一直在研究我自己的类似 的实现BigInteger,但我不知道如何保存大于Long.MAX_VALUE(我不记得实际数字)的数字。

Thanks in advance.

提前致谢。

采纳答案by corsiKa

With an int[]

int[]

From the source:

从来源:

/**
 * The magnitude of this BigInteger, in <i>big-endian</i> order: the
 * zeroth element of this array is the most-significant int of the
 * magnitude.  The magnitude must be "minimal" in that the most-significant
 * int ({@code mag[0]}) must be non-zero.  This is necessary to
 * ensure that there is exactly one representation for each BigInteger
 * value.  Note that this implies that the BigInteger zero has a
 * zero-length mag array.
 */
final int[] mag;

回答by Petr Abdulin

The most common way of representing numbers is by using the positional notation system. Numbers are written using digits to represent multiples of powers of the specified base. The base that we are most familiar with and use everyday, is base 10. When we write the number 12345 in base 10, it actually means: 12345 = 1*10^4 + 2*10^3 + 3*10^2 + 4*10^1 + 5*10^0

表示数字的最常见方式是使用位置符号系统。数字使用数字书写,以表示指定基数的幂的倍数。我们最熟悉和日常使用的基数是10。当我们把数字12345写在基数10中时,它的实际意思是:12345 = 1*10^4 + 2*10^3 + 3*10^2 + 4*10^1 + 5*10^0

Continued here...

在这里继续...

回答by ddyer

There are many ways to represent big integers. Strings of characters is simple, and anyone who has ever done long division with pencil and paper can write the arithmetic routines.

有很多方法可以表示大整数。字符串很简单,任何用铅笔和纸做过长除法的人都可以写出算术例程。