How does BigInteger store its data?

☆樱花仙子☆ 提交于 2019-12-30 03:39:06

问题


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

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

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).

Thanks in advance.


回答1:


With an 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;



回答2:


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

Continued here...




回答3:


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.



来源:https://stackoverflow.com/questions/5878603/how-does-biginteger-store-its-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!