Parsing the Java.math.BigInteger class--constructor function

Source: Internet
Author: User
Tags array length

As a result of doing homework, get acquainted with Java Biginrger class. Reading and reading, more and more interesting. Later homework finished, also can not bear to leave it, simply put all the code to study again.

At the beginning, a morning time to read up to 2 methods. But it still sticks to the stick. Below begins a little bit to open up its "hidden" secret.

First of all, to understand two questions: the purpose of the Bigingeter class-to achieve high-precision number of storage and calculation. Basic implementation mechanism--to store data with an int (32-bit) array. (Detailed in the comments in the code)

/////////////////////////////////////////////////////////////

Properties in the BigInteger class: {

int Signum; Sign bit, negative number is-1, zero is 0, positive number is 1

Int[] Mag; The magnitude of this BigInteger, the value of a large number//other auxiliary variable temporarily without first looking

}

First, the following constructor is analyzed (construction five: 1. Check whether it complies with standard 2. Zero 3.mag assignment 4. Go to Mag in 5. Sign bit assignment)

1. Construct the BigInteger using a byte (8-bit) array:

/////////////////////////////////////////////////////////////////////

Public BigInteger (byte[] val) {
if (Val.length = = 0)
throw new NumberFormatException ("zero length BigInteger");//incoming array length is zero, error

if (Val[0] < 0) {
Mag = makepositive (val);
Signum =-1; If the first value of the array is a negative number, the array is converted to a positive deposit of mag,signum-1
} else {
Mag = Stripleadingzerobytes (val); If non-negative, you can directly remove the previous invalid zero, and then assign to Mag
Signum = (Mag.length = = 0? 0:1);

}

}

Let's take a look at the function of the specific call

///////////////////////////////////////////////////////////////////////////

private static int[] Stripleadingzerobytes (byte a[]) {
int bytelength = A.length;
int keep;

Find First Nonzero byte
for (keep=0; keep<a.length&& a[keep]==0; keep++)//Find first significant bit and use keep to record
;

Allocate new array and copy relevant Partof input array
int intlength = ((bytelength-keep) + 3)/4; Calculates the length of the int[], BYTE[1/2/3/4] corresponds to int[1]

Int[] result = new Int[intlength];
int b = byteLength-1;
for (int i = intLength-1; I >= 0; i--) {
Result[i] = a[b--] & 0xff; Assign value to int[], &0xff the effect of eliminating the first 24 bits of int

(The computer uses the complement to store data, and if you assign a byte value of the first bit "1" to int, the first 24 will be "1")

int bytesremaining = b-keep + 1;
int bytestotransfer = Math.min (3, bytesremaining);
for (int j=8; J <= 8*bytestotransfer; j + = 8)
Result[i] |= ((a[b--] & 0xff) << j); SHIFT, move 8 bits at a time, and then perform or calculate
}
return result;
}

//////////////////////////////////////////////////////////////

  private static int[]makepositive (byte a[]) {int Keep, k;       int bytelength = a.length;& nbsp;//Find First Non-sign (0xff) byte of Inputfor (keep=0; keep<bytelength&& a[keep]==-1; keep++)//Find the non-sign bit (here I looked at it for a long time to understand it). If the a[]=-1, that is, the computer binary is "11111111", in the int type is all "1" the first few are considered to be the sign bit. To convert to a positive int value, you only need the latter few.    ;        for (k=keep; k<bytelength&& a[k]==0; k++)    & nbsp; //because the first value of the incoming parameter array must be negative (by the constructor), so do not consider going to 0, the function of the variable k is only to judge the need for "extra" bits    ; int extrabyte = (k==bytelength ) ? 1:0;       //If all except the sign bit is "0", then "extra" 1 bits are required to store the data        int intlength = ((bytelength-keep + extrabyte) + 3)/4;int result[] = new int[intlength];        int b = bytelength-1;       for (int i = intLength-1; I >= 0;i--) {           result[i]= a[b--] & 0 xff;           Intnumbytestotransfer = Math.min (3, b-keep+1);           if (Numbytestotransfer < 0)               Numbytestotransfer = 0;           for (intj=8; J <= 8*numbytes Totransfer; J + = 8)               Result[i] |= ((a[b--]& 0xff) << j);   &NB Sp       //maskindicates which bits must be complemented           int MA SK =-1 >>> (8* (3-numbytestotransfer))  //negative value to positive, that is, from the original code to reverse code            result[ i]= ~result[i] & mask;      } //Add one to one's complement to generate ' scomplementfor (int i=result.length-1; i>=0; i--) {           result[i]= (int) ((Result[i] & Long_mask) + 1)  //long Long_mask =0xffff FFFFL: For bitwise operations, regardless of the int symbol problem    if (result[i]! = 0)    //(this place also deceived me for a long time) suddenly pitiful, actually is +1 afterNot zero, that is, do not need to carry, break out of it!               break;      } return result;    } 2.   is constructed using an int (32-bit) array biginteger:///////////////////////////////////////////////////////////// Private BigInteger (int[] val) {if (val.length = = 0)    throw newnumberformatexception ("Zero length BigInteger") ;  if (Val[0] < 0) {           Mag =makepositive (val);   signum =-1;} else {   mag =trustedstripleadingzeroints (val);   signum = (Mag.length = = 0? 0:1);}    }  and byte[] are constructed in the same way and are simpler and not restated. One thing to note, here is the use of trustedstripleadingzeroints can be trusted to go to 0 method, and the difference between stripleadingzeroints is that for a trustworthy go 0 method, if there is no invalid zero, then directly return the original array, not to copy.    Change to: http://blog.sina.com.cn/s/blog_6c58b3bf01013wer.html

Parsing the Java.math.BigInteger class-constructor

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.