src/share/classes/java/math/BigInteger.java

Print this page
rev 9348 : 8035279: Clean up internal deprecations in BigInteger
Summary: Rename pertinent private instance variables to describe what they actually represent.
Reviewed-by: psandoz


 125      * The signum of this BigInteger: -1 for negative, 0 for zero, or
 126      * 1 for positive.  Note that the BigInteger zero <i>must</i> have
 127      * a signum of 0.  This is necessary to ensures that there is exactly one
 128      * representation for each BigInteger value.
 129      *
 130      * @serial
 131      */
 132     final int signum;
 133 
 134     /**
 135      * The magnitude of this BigInteger, in <i>big-endian</i> order: the
 136      * zeroth element of this array is the most-significant int of the
 137      * magnitude.  The magnitude must be "minimal" in that the most-significant
 138      * int ({@code mag[0]}) must be non-zero.  This is necessary to
 139      * ensure that there is exactly one representation for each BigInteger
 140      * value.  Note that this implies that the BigInteger zero has a
 141      * zero-length mag array.
 142      */
 143     final int[] mag;
 144 
 145     // These "redundant fields" are initialized with recognizable nonsense
 146     // values, and cached the first time they are needed (or never, if they
 147     // aren't needed).
 148 
 149      /**
 150      * One plus the bitCount of this BigInteger. Zeros means unitialized.
 151      *
 152      * @serial
 153      * @see #bitCount
 154      * @deprecated Deprecated since logical value is offset from stored
 155      * value and correction factor is applied in accessor method.
 156      */
 157     @Deprecated
 158     private int bitCount;
 159 
 160     /**
 161      * One plus the bitLength of this BigInteger. Zeros means unitialized.
 162      * (either value is acceptable).
 163      *
 164      * @serial
 165      * @see #bitLength()
 166      * @deprecated Deprecated since logical value is offset from stored
 167      * value and correction factor is applied in accessor method.
 168      */
 169     @Deprecated
 170     private int bitLength;
 171 
 172     /**
 173      * Two plus the lowest set bit of this BigInteger, as returned by
 174      * getLowestSetBit().
 175      *
 176      * @serial
 177      * @see #getLowestSetBit
 178      * @deprecated Deprecated since logical value is offset from stored
 179      * value and correction factor is applied in accessor method.
 180      */
 181     @Deprecated
 182     private int lowestSetBit;
 183 
 184     /**
 185      * Two plus the index of the lowest-order int in the magnitude of this
 186      * BigInteger that contains a nonzero int, or -2 (either value is acceptable).
 187      * The least significant int has int-number 0, the next int in order of
 188      * increasing significance has int-number 1, and so forth.
 189      * @deprecated Deprecated since logical value is offset from stored
 190      * value and correction factor is applied in accessor method.


 191      */
 192     @Deprecated
 193     private int firstNonzeroIntNum;
 194 
 195     /**
 196      * This mask is used to obtain the value of an int as if it were unsigned.
 197      */
 198     final static long LONG_MASK = 0xffffffffL;
 199 
 200     /**
 201      * This constant limits {@code mag.length} of BigIntegers to the supported
 202      * range.
 203      */
 204     private static final int MAX_MAG_LENGTH = Integer.MAX_VALUE / Integer.SIZE + 1; // (1 << 26)
 205 
 206     /**
 207      * Bit lengths larger than this constant can cause overflow in searchLen
 208      * calculation and in BitSieve.singleSearch method.
 209      */
 210     private static final  int PRIME_SEARCH_BIT_LENGTH_LIMIT = 500000000;
 211 
 212     /**
 213      * The threshold value for using Karatsuba multiplication.  If the number


3223         int intNum = n >>> 5;
3224         int[] result = new int[Math.max(intLength(), intNum+2)];
3225 
3226         for (int i=0; i < result.length; i++)
3227             result[result.length-i-1] = getInt(i);
3228 
3229         result[result.length-intNum-1] ^= (1 << (n & 31));
3230 
3231         return valueOf(result);
3232     }
3233 
3234     /**
3235      * Returns the index of the rightmost (lowest-order) one bit in this
3236      * BigInteger (the number of zero bits to the right of the rightmost
3237      * one bit).  Returns -1 if this BigInteger contains no one bits.
3238      * (Computes {@code (this == 0? -1 : log2(this & -this))}.)
3239      *
3240      * @return index of the rightmost one bit in this BigInteger.
3241      */
3242     public int getLowestSetBit() {
3243         @SuppressWarnings("deprecation") int lsb = lowestSetBit - 2;
3244         if (lsb == -2) {  // lowestSetBit not initialized yet
3245             lsb = 0;
3246             if (signum == 0) {
3247                 lsb -= 1;
3248             } else {
3249                 // Search for lowest order nonzero int
3250                 int i,b;
3251                 for (i=0; (b = getInt(i)) == 0; i++)
3252                     ;
3253                 lsb += (i << 5) + Integer.numberOfTrailingZeros(b);
3254             }
3255             lowestSetBit = lsb + 2;
3256         }
3257         return lsb;
3258     }
3259 
3260 
3261     // Miscellaneous Bit Operations
3262 
3263     /**
3264      * Returns the number of bits in the minimal two's-complement
3265      * representation of this BigInteger, <i>excluding</i> a sign bit.
3266      * For positive BigIntegers, this is equivalent to the number of bits in
3267      * the ordinary binary representation.  (Computes
3268      * {@code (ceil(log2(this < 0 ? -this : this+1)))}.)
3269      *
3270      * @return number of bits in the minimal two's-complement
3271      *         representation of this BigInteger, <i>excluding</i> a sign bit.
3272      */
3273     public int bitLength() {
3274         @SuppressWarnings("deprecation") int n = bitLength - 1;
3275         if (n == -1) { // bitLength not initialized yet
3276             int[] m = mag;
3277             int len = m.length;
3278             if (len == 0) {
3279                 n = 0; // offset by one to initialize
3280             }  else {
3281                 // Calculate the bit length of the magnitude
3282                 int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]);
3283                  if (signum < 0) {
3284                      // Check if magnitude is a power of two
3285                      boolean pow2 = (Integer.bitCount(mag[0]) == 1);
3286                      for (int i=1; i< len && pow2; i++)
3287                          pow2 = (mag[i] == 0);
3288 
3289                      n = (pow2 ? magBitLength -1 : magBitLength);
3290                  } else {
3291                      n = magBitLength;
3292                  }
3293             }
3294             bitLength = n + 1;
3295         }
3296         return n;
3297     }
3298 
3299     /**
3300      * Returns the number of bits in the two's complement representation
3301      * of this BigInteger that differ from its sign bit.  This method is
3302      * useful when implementing bit-vector style sets atop BigIntegers.
3303      *
3304      * @return number of bits in the two's complement representation
3305      *         of this BigInteger that differ from its sign bit.
3306      */
3307     public int bitCount() {
3308         @SuppressWarnings("deprecation") int bc = bitCount - 1;
3309         if (bc == -1) {  // bitCount not initialized yet
3310             bc = 0;      // offset by one to initialize
3311             // Count the bits in the magnitude
3312             for (int i=0; i < mag.length; i++)
3313                 bc += Integer.bitCount(mag[i]);
3314             if (signum < 0) {
3315                 // Count the trailing zeros in the magnitude
3316                 int magTrailingZeroCount = 0, j;
3317                 for (j=mag.length-1; mag[j] == 0; j--)
3318                     magTrailingZeroCount += 32;
3319                 magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]);
3320                 bc += magTrailingZeroCount - 1;
3321             }
3322             bitCount = bc + 1;
3323         }
3324         return bc;
3325     }
3326 
3327     // Primality Testing
3328 
3329     /**
3330      * Returns {@code true} if this BigInteger is probably prime,
3331      * {@code false} if it's definitely composite.  If
3332      * {@code certainty} is &le; 0, {@code true} is
3333      * returned.
3334      *
3335      * @param  certainty a measure of the uncertainty that the caller is
3336      *         willing to tolerate: if the call returns {@code true}
3337      *         the probability that this BigInteger is prime exceeds
3338      *         (1 - 1/2<sup>{@code certainty}</sup>).  The execution time of
3339      *         this method is proportional to the value of this parameter.
3340      * @return {@code true} if this BigInteger is probably prime,
3341      *         {@code false} if it's definitely composite.
3342      */


3605             buf.append(digitGroup[i]);
3606         }
3607         return buf.toString();
3608     }
3609 
3610     /**
3611      * Converts the specified BigInteger to a string and appends to
3612      * {@code sb}.  This implements the recursive Schoenhage algorithm
3613      * for base conversions.
3614      * <p/>
3615      * See Knuth, Donald,  _The Art of Computer Programming_, Vol. 2,
3616      * Answers to Exercises (4.4) Question 14.
3617      *
3618      * @param u      The number to convert to a string.
3619      * @param sb     The StringBuilder that will be appended to in place.
3620      * @param radix  The base to convert to.
3621      * @param digits The minimum number of digits to pad to.
3622      */
3623     private static void toString(BigInteger u, StringBuilder sb, int radix,
3624                                  int digits) {
3625         /* If we're smaller than a certain threshold, use the smallToString
3626            method, padding with leading zeroes when necessary. */
3627         if (u.mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) {
3628             String s = u.smallToString(radix);
3629 
3630             // Pad with internal zeros if necessary.
3631             // Don't pad if we're at the beginning of the string.
3632             if ((s.length() < digits) && (sb.length() > 0)) {
3633                 for (int i=s.length(); i < digits; i++) { // May be a faster way to
3634                     sb.append('0');                    // do this?
3635                 }
3636             }
3637 
3638             sb.append(s);
3639             return;
3640         }
3641 
3642         int b, n;
3643         b = u.bitLength();
3644 
3645         // Calculate a value for n in the equation radix^(2^n) = u
3646         // and subtract 1 from that value.  This is used to find the
3647         // cache index that contains the best value to divide u.
3648         n = (int) Math.round(Math.log(b * LOG_TWO / logCache[radix]) / LOG_TWO - 1.0);
3649         BigInteger v = getRadixConversionCache(radix, n);
3650         BigInteger[] results;
3651         results = u.divideAndRemainder(v);
3652 
3653         int expectedDigits = 1 << n;
3654 


4171      * representation (int 0 is the least significant).  The int number can
4172      * be arbitrarily high (values are logically preceded by infinitely many
4173      * sign ints).
4174      */
4175     private int getInt(int n) {
4176         if (n < 0)
4177             return 0;
4178         if (n >= mag.length)
4179             return signInt();
4180 
4181         int magInt = mag[mag.length-n-1];
4182 
4183         return (signum >= 0 ? magInt :
4184                 (n <= firstNonzeroIntNum() ? -magInt : ~magInt));
4185     }
4186 
4187     /**
4188      * Returns the index of the int that contains the first nonzero int in the
4189      * little-endian binary representation of the magnitude (int 0 is the
4190      * least significant). If the magnitude is zero, return value is undefined.



4191      */
4192     private int firstNonzeroIntNum() {
4193         int fn = firstNonzeroIntNum - 2;
4194         if (fn == -2) { // firstNonzeroIntNum not initialized yet
4195             fn = 0;
4196 
4197             // Search for the first nonzero int
4198             int i;
4199             int mlen = mag.length;
4200             for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)
4201                 ;
4202             fn = mlen - i - 1;
4203             firstNonzeroIntNum = fn + 2; // offset by two to initialize
4204         }
4205         return fn;
4206     }
4207 
4208     /** use serialVersionUID from JDK 1.1. for interoperability */
4209     private static final long serialVersionUID = -8287574255936472291L;
4210 
4211     /**
4212      * Serializable fields for BigInteger.
4213      *
4214      * @serialField signum  int
4215      *              signum of this BigInteger.
4216      * @serialField magnitude int[]
4217      *              magnitude array of this BigInteger.
4218      * @serialField bitCount  int
4219      *              number of bits in this BigInteger
4220      * @serialField bitLength int
4221      *              the number of bits in the minimal two's-complement
4222      *              representation of this BigInteger
4223      * @serialField lowestSetBit int
4224      *              lowest set bit in the twos complement representation
4225      */
4226     private static final ObjectStreamField[] serialPersistentFields = {
4227         new ObjectStreamField("signum", Integer.TYPE),
4228         new ObjectStreamField("magnitude", byte[].class),
4229         new ObjectStreamField("bitCount", Integer.TYPE),
4230         new ObjectStreamField("bitLength", Integer.TYPE),
4231         new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE),
4232         new ObjectStreamField("lowestSetBit", Integer.TYPE)
4233         };
4234 
4235     /**
4236      * Reconstitute the {@code BigInteger} instance from a stream (that is,
4237      * deserialize it). The magnitude is read in as an array of bytes
4238      * for historical reasons, but it is converted to an array of ints
4239      * and the byte array is discarded.
4240      * Note:
4241      * The current convention is to initialize the cache fields, bitCount,
4242      * bitLength and lowestSetBit, to 0 rather than some other marker value.
4243      * Therefore, no explicit action to set these fields needs to be taken in
4244      * readObject because those fields already have a 0 value be default since
4245      * defaultReadObject is not being used.
4246      */
4247     private void readObject(java.io.ObjectInputStream s)
4248         throws java.io.IOException, ClassNotFoundException {
4249         /*
4250          * In order to maintain compatibility with previous serialized forms,
4251          * the magnitude of a BigInteger is serialized as an array of bytes.
4252          * The magnitude field is used as a temporary store for the byte array
4253          * that is deserialized. The cached computation fields should be
4254          * transient but are serialized for compatibility reasons.
4255          */
4256 
4257         // prepare to read the alternate persistent fields
4258         ObjectInputStream.GetField fields = s.readFields();
4259 
4260         // Read the alternate persistent fields that we care about
4261         int sign = fields.get("signum", -2);
4262         byte[] magnitude = (byte[])fields.get("magnitude", null);
4263 
4264         // Validate signum
4265         if (sign < -1 || sign > 1) {




 125      * The signum of this BigInteger: -1 for negative, 0 for zero, or
 126      * 1 for positive.  Note that the BigInteger zero <i>must</i> have
 127      * a signum of 0.  This is necessary to ensures that there is exactly one
 128      * representation for each BigInteger value.
 129      *
 130      * @serial
 131      */
 132     final int signum;
 133 
 134     /**
 135      * The magnitude of this BigInteger, in <i>big-endian</i> order: the
 136      * zeroth element of this array is the most-significant int of the
 137      * magnitude.  The magnitude must be "minimal" in that the most-significant
 138      * int ({@code mag[0]}) must be non-zero.  This is necessary to
 139      * ensure that there is exactly one representation for each BigInteger
 140      * value.  Note that this implies that the BigInteger zero has a
 141      * zero-length mag array.
 142      */
 143     final int[] mag;
 144 
 145     // The following fields are stable variables. A stable variable's value
 146     // changes at most once from the default zero value to a non-zero stable
 147     // value. A stable value is calculated lazily on demand.
 148 
 149     /**
 150      * One plus the bitCount of this BigInteger. This is a stable variable.
 151      *
 152      * @serial
 153      * @see #bitCount


 154      */
 155     private int bitCountPlusOne;

 156 
 157     /**
 158      * One plus the bitLength of this BigInteger. This is a stable variable.
 159      * (either value is acceptable).
 160      *
 161      * @serial
 162      * @see #bitLength()


 163      */
 164     private int bitLengthPlusOne;

 165 
 166     /**
 167      * Two plus the lowest set bit of this BigInteger. This is a stable variable.

 168      *
 169      * @serial
 170      * @see #getLowestSetBit


 171      */
 172     private int lowestSetBitPlusTwo;

 173 
 174     /**
 175      * Two plus the index of the lowest-order int in the magnitude of this
 176      * BigInteger that contains a nonzero int. This is a stable variable. The
 177      * least significant int has int-number 0, the next int in order of
 178      * increasing significance has int-number 1, and so forth.
 179      *
 180      * <p>Note: never used for a BigInteger with a magnitude of zero.
 181      *
 182      * @see #firstNonzeroIntNum()
 183      */
 184     private int firstNonzeroIntNumPlusTwo;

 185 
 186     /**
 187      * This mask is used to obtain the value of an int as if it were unsigned.
 188      */
 189     final static long LONG_MASK = 0xffffffffL;
 190 
 191     /**
 192      * This constant limits {@code mag.length} of BigIntegers to the supported
 193      * range.
 194      */
 195     private static final int MAX_MAG_LENGTH = Integer.MAX_VALUE / Integer.SIZE + 1; // (1 << 26)
 196 
 197     /**
 198      * Bit lengths larger than this constant can cause overflow in searchLen
 199      * calculation and in BitSieve.singleSearch method.
 200      */
 201     private static final  int PRIME_SEARCH_BIT_LENGTH_LIMIT = 500000000;
 202 
 203     /**
 204      * The threshold value for using Karatsuba multiplication.  If the number


3214         int intNum = n >>> 5;
3215         int[] result = new int[Math.max(intLength(), intNum+2)];
3216 
3217         for (int i=0; i < result.length; i++)
3218             result[result.length-i-1] = getInt(i);
3219 
3220         result[result.length-intNum-1] ^= (1 << (n & 31));
3221 
3222         return valueOf(result);
3223     }
3224 
3225     /**
3226      * Returns the index of the rightmost (lowest-order) one bit in this
3227      * BigInteger (the number of zero bits to the right of the rightmost
3228      * one bit).  Returns -1 if this BigInteger contains no one bits.
3229      * (Computes {@code (this == 0? -1 : log2(this & -this))}.)
3230      *
3231      * @return index of the rightmost one bit in this BigInteger.
3232      */
3233     public int getLowestSetBit() {
3234         int lsb = lowestSetBitPlusTwo - 2;
3235         if (lsb == -2) {  // lowestSetBit not initialized yet
3236             lsb = 0;
3237             if (signum == 0) {
3238                 lsb -= 1;
3239             } else {
3240                 // Search for lowest order nonzero int
3241                 int i,b;
3242                 for (i=0; (b = getInt(i)) == 0; i++)
3243                     ;
3244                 lsb += (i << 5) + Integer.numberOfTrailingZeros(b);
3245             }
3246             lowestSetBitPlusTwo = lsb + 2;
3247         }
3248         return lsb;
3249     }
3250 
3251 
3252     // Miscellaneous Bit Operations
3253 
3254     /**
3255      * Returns the number of bits in the minimal two's-complement
3256      * representation of this BigInteger, <i>excluding</i> a sign bit.
3257      * For positive BigIntegers, this is equivalent to the number of bits in
3258      * the ordinary binary representation.  (Computes
3259      * {@code (ceil(log2(this < 0 ? -this : this+1)))}.)
3260      *
3261      * @return number of bits in the minimal two's-complement
3262      *         representation of this BigInteger, <i>excluding</i> a sign bit.
3263      */
3264     public int bitLength() {
3265         int n = bitLengthPlusOne - 1;
3266         if (n == -1) { // bitLength not initialized yet
3267             int[] m = mag;
3268             int len = m.length;
3269             if (len == 0) {
3270                 n = 0; // offset by one to initialize
3271             }  else {
3272                 // Calculate the bit length of the magnitude
3273                 int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]);
3274                  if (signum < 0) {
3275                      // Check if magnitude is a power of two
3276                      boolean pow2 = (Integer.bitCount(mag[0]) == 1);
3277                      for (int i=1; i< len && pow2; i++)
3278                          pow2 = (mag[i] == 0);
3279 
3280                      n = (pow2 ? magBitLength -1 : magBitLength);
3281                  } else {
3282                      n = magBitLength;
3283                  }
3284             }
3285             bitLengthPlusOne = n + 1;
3286         }
3287         return n;
3288     }
3289 
3290     /**
3291      * Returns the number of bits in the two's complement representation
3292      * of this BigInteger that differ from its sign bit.  This method is
3293      * useful when implementing bit-vector style sets atop BigIntegers.
3294      *
3295      * @return number of bits in the two's complement representation
3296      *         of this BigInteger that differ from its sign bit.
3297      */
3298     public int bitCount() {
3299         int bc = bitCountPlusOne - 1;
3300         if (bc == -1) {  // bitCount not initialized yet
3301             bc = 0;      // offset by one to initialize
3302             // Count the bits in the magnitude
3303             for (int i=0; i < mag.length; i++)
3304                 bc += Integer.bitCount(mag[i]);
3305             if (signum < 0) {
3306                 // Count the trailing zeros in the magnitude
3307                 int magTrailingZeroCount = 0, j;
3308                 for (j=mag.length-1; mag[j] == 0; j--)
3309                     magTrailingZeroCount += 32;
3310                 magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]);
3311                 bc += magTrailingZeroCount - 1;
3312             }
3313             bitCountPlusOne = bc + 1;
3314         }
3315         return bc;
3316     }
3317 
3318     // Primality Testing
3319 
3320     /**
3321      * Returns {@code true} if this BigInteger is probably prime,
3322      * {@code false} if it's definitely composite.  If
3323      * {@code certainty} is &le; 0, {@code true} is
3324      * returned.
3325      *
3326      * @param  certainty a measure of the uncertainty that the caller is
3327      *         willing to tolerate: if the call returns {@code true}
3328      *         the probability that this BigInteger is prime exceeds
3329      *         (1 - 1/2<sup>{@code certainty}</sup>).  The execution time of
3330      *         this method is proportional to the value of this parameter.
3331      * @return {@code true} if this BigInteger is probably prime,
3332      *         {@code false} if it's definitely composite.
3333      */


3596             buf.append(digitGroup[i]);
3597         }
3598         return buf.toString();
3599     }
3600 
3601     /**
3602      * Converts the specified BigInteger to a string and appends to
3603      * {@code sb}.  This implements the recursive Schoenhage algorithm
3604      * for base conversions.
3605      * <p/>
3606      * See Knuth, Donald,  _The Art of Computer Programming_, Vol. 2,
3607      * Answers to Exercises (4.4) Question 14.
3608      *
3609      * @param u      The number to convert to a string.
3610      * @param sb     The StringBuilder that will be appended to in place.
3611      * @param radix  The base to convert to.
3612      * @param digits The minimum number of digits to pad to.
3613      */
3614     private static void toString(BigInteger u, StringBuilder sb, int radix,
3615                                  int digits) {
3616         // If we're smaller than a certain threshold, use the smallToString
3617         // method, padding with leading zeroes when necessary.
3618         if (u.mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) {
3619             String s = u.smallToString(radix);
3620 
3621             // Pad with internal zeros if necessary.
3622             // Don't pad if we're at the beginning of the string.
3623             if ((s.length() < digits) && (sb.length() > 0)) {
3624                 for (int i=s.length(); i < digits; i++) {
3625                     sb.append('0');
3626                 }
3627             }
3628 
3629             sb.append(s);
3630             return;
3631         }
3632 
3633         int b, n;
3634         b = u.bitLength();
3635 
3636         // Calculate a value for n in the equation radix^(2^n) = u
3637         // and subtract 1 from that value.  This is used to find the
3638         // cache index that contains the best value to divide u.
3639         n = (int) Math.round(Math.log(b * LOG_TWO / logCache[radix]) / LOG_TWO - 1.0);
3640         BigInteger v = getRadixConversionCache(radix, n);
3641         BigInteger[] results;
3642         results = u.divideAndRemainder(v);
3643 
3644         int expectedDigits = 1 << n;
3645 


4162      * representation (int 0 is the least significant).  The int number can
4163      * be arbitrarily high (values are logically preceded by infinitely many
4164      * sign ints).
4165      */
4166     private int getInt(int n) {
4167         if (n < 0)
4168             return 0;
4169         if (n >= mag.length)
4170             return signInt();
4171 
4172         int magInt = mag[mag.length-n-1];
4173 
4174         return (signum >= 0 ? magInt :
4175                 (n <= firstNonzeroIntNum() ? -magInt : ~magInt));
4176     }
4177 
4178     /**
4179     * Returns the index of the int that contains the first nonzero int in the
4180     * little-endian binary representation of the magnitude (int 0 is the
4181     * least significant). If the magnitude is zero, return value is undefined.
4182     *
4183     * <p>Note: never used for a BigInteger with a magnitude of zero.
4184     * @see #getInt.
4185     */
4186     private int firstNonzeroIntNum() {
4187         int fn = firstNonzeroIntNumPlusTwo - 2;
4188         if (fn == -2) { // firstNonzeroIntNum not initialized yet


4189             // Search for the first nonzero int
4190             int i;
4191             int mlen = mag.length;
4192             for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)
4193                 ;
4194             fn = mlen - i - 1;
4195             firstNonzeroIntNumPlusTwo = fn + 2; // offset by two to initialize
4196         }
4197         return fn;
4198     }
4199 
4200     /** use serialVersionUID from JDK 1.1. for interoperability */
4201     private static final long serialVersionUID = -8287574255936472291L;
4202 
4203     /**
4204      * Serializable fields for BigInteger.
4205      *
4206      * @serialField signum  int
4207      *              signum of this BigInteger.
4208      * @serialField magnitude int[]
4209      *              magnitude array of this BigInteger.
4210      * @serialField bitCount  int
4211      *              number of bits in this BigInteger
4212      * @serialField bitLength int
4213      *              the number of bits in the minimal two's-complement
4214      *              representation of this BigInteger
4215      * @serialField lowestSetBit int
4216      *              lowest set bit in the twos complement representation
4217      */
4218     private static final ObjectStreamField[] serialPersistentFields = {
4219         new ObjectStreamField("signum", Integer.TYPE),
4220         new ObjectStreamField("magnitude", byte[].class),
4221         new ObjectStreamField("bitCount", Integer.TYPE),
4222         new ObjectStreamField("bitLength", Integer.TYPE),
4223         new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE),
4224         new ObjectStreamField("lowestSetBit", Integer.TYPE)
4225         };
4226 
4227     /**
4228      * Reconstitute the {@code BigInteger} instance from a stream (that is,
4229      * deserialize it). The magnitude is read in as an array of bytes
4230      * for historical reasons, but it is converted to an array of ints
4231      * and the byte array is discarded.
4232      * Note:
4233      * The current convention is to initialize the cache fields, bitCountPlusOne,
4234      * bitLengthPlusOne and lowestSetBitPlusTwo, to 0 rather than some other
4235      * marker value. Therefore, no explicit action to set these fields needs to
4236      * be taken in readObject because those fields already have a 0 value be
4237      * default since defaultReadObject is not being used.
4238      */
4239     private void readObject(java.io.ObjectInputStream s)
4240         throws java.io.IOException, ClassNotFoundException {
4241         /*
4242          * In order to maintain compatibility with previous serialized forms,
4243          * the magnitude of a BigInteger is serialized as an array of bytes.
4244          * The magnitude field is used as a temporary store for the byte array
4245          * that is deserialized. The cached computation fields should be
4246          * transient but are serialized for compatibility reasons.
4247          */
4248 
4249         // prepare to read the alternate persistent fields
4250         ObjectInputStream.GetField fields = s.readFields();
4251 
4252         // Read the alternate persistent fields that we care about
4253         int sign = fields.get("signum", -2);
4254         byte[] magnitude = (byte[])fields.get("magnitude", null);
4255 
4256         // Validate signum
4257         if (sign < -1 || sign > 1) {