Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does BigInteger store its data?

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.

like image 697
Jon Egeland Avatar asked May 04 '11 04:05

Jon Egeland


People also ask

How is BigInteger stored?

A BigInteger is just a sign and an array of digits, from the least significant to most significant: // n = -123 var n = { sign: -1, digits: [3, 2, 1] }; The digits look backwards, but by storing the digits with the ones place first, they will line up with other numbers correctly even if they have different lengths.

How does BigInteger work in Java?

BigInteger represents immutable arbitrary-precision integers. It is similar to the primitive integer types but allows arbitrary large values. It is used when integers involved are larger than the limit of long type. For example, the factorial of 50 is 30414093201713378043612608166064768844377641568960512000000000000.

How many bits can BigInteger hold?

The BigInteger class stores a number as an array of unsigned, 32-bit integer "digits" with a radix, or base, of 4294967296.

Is BigInteger immutable?

Like strings, BigInteger objects are immutable. Methods like add , multiply , and pow all return new BigIntegers, rather than modify an existing one. Internally, a BigInteger is implemented using an array of int s, similar to the way a string is implemented using an array of char s.


1 Answers

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; 
like image 69
corsiKa Avatar answered Oct 14 '22 13:10

corsiKa