Home | History | Annotate | Download | only in math
      1 /*
      2  *  Licensed to the Apache Software Foundation (ASF) under one or more
      3  *  contributor license agreements.  See the NOTICE file distributed with
      4  *  this work for additional information regarding copyright ownership.
      5  *  The ASF licenses this file to You under the Apache License, Version 2.0
      6  *  (the "License"); you may not use this file except in compliance with
      7  *  the License.  You may obtain a copy of the License at
      8  *
      9  *     http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  *  Unless required by applicable law or agreed to in writing, software
     12  *  distributed under the License is distributed on an "AS IS" BASIS,
     13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  *  See the License for the specific language governing permissions and
     15  *  limitations under the License.
     16  */
     17 
     18 // BEGIN android-note
     19 // Since the original Harmony Code of the BigInteger class was strongly modified,
     20 // in order to use the more efficient OpenSSL BIGNUM implementation,
     21 // no android-modification-tags were placed, at all.
     22 // END android-note
     23 
     24 package java.math;
     25 
     26 import java.io.IOException;
     27 import java.io.ObjectInputStream;
     28 import java.io.ObjectOutputStream;
     29 import java.util.Random;
     30 import java.io.Serializable;
     31 
     32 import org.apache.harmony.math.internal.nls.Messages;
     33 
     34 /**
     35  * This class represents immutable integer numbers of arbitrary length. Large
     36  * numbers are typically used in security applications and therefore BigIntegers
     37  * offer dedicated functionality like the generation of large prime numbers or
     38  * the computation of modular inverse.
     39  * <p>
     40  * Since the class was modeled to offer all the functionality as the {@link Integer}
     41  * class does, it provides even methods that operate bitwise on a two's
     42  * complement representation of large integers. Note however that the
     43  * implementations favors an internal representation where magnitude and sign
     44  * are treated separately. Hence such operations are inefficient and should be
     45  * discouraged. In simple words: Do NOT implement any bit fields based on
     46  * BigInteger.
     47  * <p>
     48  * <b>Implementation Note:</b> <br>
     49  * The native OpenSSL library with its BIGNUM operations covers all the
     50  * meaningful functionality (everything but bit level operations).
     51  */
     52 public class BigInteger extends Number implements Comparable<BigInteger>,
     53         Serializable {
     54 
     55     /** This is the serialVersionUID used by the sun implementation. */
     56     private static final long serialVersionUID = -8287574255936472291L;
     57 
     58     transient BigInt bigInt;
     59     transient private boolean bigIntIsValid = false;
     60     transient private boolean oldReprIsValid = false;
     61 
     62     void establishOldRepresentation(String caller) {
     63         if (!oldReprIsValid) {
     64             sign = bigInt.sign();
     65             if (sign != 0) digits = bigInt.littleEndianIntsMagnitude();
     66             else digits = new int[] { 0 };
     67             numberLength = digits.length;
     68             oldReprIsValid = true;
     69         }
     70     }
     71 
     72     // The name is confusing:
     73     // This method is called whenever the old representation has been written.
     74     // It ensures that the new representation will be established on demand.
     75     //
     76     BigInteger withNewRepresentation(String caller) {
     77         bigIntIsValid = false;
     78         return this;
     79     }
     80 
     81     void validate(String caller, String param) {
     82         if (bigIntIsValid) {
     83             if (bigInt == null)
     84                 System.out.print("Claiming bigIntIsValid BUT bigInt == null, ");
     85             else if (bigInt.getNativeBIGNUM() == 0)
     86                 System.out.print("Claiming bigIntIsValid BUT bigInt.bignum == 0, ");
     87         }
     88         else {
     89             if (oldReprIsValid) { // establish new representation
     90                 if (bigInt == null) bigInt = new BigInt();
     91                 bigInt.putLittleEndianInts(digits, (sign < 0));
     92                 bigIntIsValid = true;
     93             }
     94             else {
     95                 throw new IllegalArgumentException(caller + ":" + param);
     96             }
     97         }
     98     }
     99 
    100     static void validate1(String caller, BigInteger a) {
    101         a.validate(caller, "1");
    102     }
    103 
    104     static void validate2(String caller, BigInteger a, BigInteger b) {
    105         a.validate(caller, "1");
    106         b.validate(caller, "2");
    107     }
    108 
    109     static void validate3(String caller, BigInteger a, BigInteger b, BigInteger c) {
    110         a.validate(caller, "1");
    111         b.validate(caller, "2");
    112         c.validate(caller, "3");
    113     }
    114 
    115     static void validate4(String caller, BigInteger a, BigInteger b, BigInteger c, BigInteger d) {
    116         a.validate(caller, "1");
    117         b.validate(caller, "2");
    118         c.validate(caller, "3");
    119         d.validate(caller, "4");
    120     }
    121 
    122     /** The magnitude of this in the little-endian representation. */
    123     transient int digits[];
    124 
    125     /** The length of this in measured in ints. Can be less than digits.length(). */
    126     transient int numberLength;
    127 
    128     /** The sign of this. */
    129     transient int sign;
    130 
    131     /**
    132      * The {@code BigInteger} constant 0.
    133      */
    134     public static final BigInteger ZERO = new BigInteger(0, 0);
    135 
    136     /**
    137      * The {@code BigInteger} constant 1.
    138      */
    139     public static final BigInteger ONE = new BigInteger(1, 1);
    140 
    141     /**
    142      * The {@code BigInteger} constant 10.
    143      */
    144     public static final BigInteger TEN = new BigInteger(1, 10);
    145 
    146     /** The {@code BigInteger} constant -1. */
    147     static final BigInteger MINUS_ONE = new BigInteger(-1, 1);
    148 
    149     /** The {@code BigInteger} constant 0 used for comparison. */
    150     static final int EQUALS = 0;
    151 
    152     /** The {@code BigInteger} constant 1 used for comparison. */
    153     static final int GREATER = 1;
    154 
    155     /** The {@code BigInteger} constant -1 used for comparison. */
    156     static final int LESS = -1;
    157 
    158     /** All the {@code BigInteger} numbers in the range [0,10] are cached. */
    159     static final BigInteger[] SMALL_VALUES = { ZERO, ONE, new BigInteger(1, 2),
    160             new BigInteger(1, 3), new BigInteger(1, 4), new BigInteger(1, 5),
    161             new BigInteger(1, 6), new BigInteger(1, 7), new BigInteger(1, 8),
    162             new BigInteger(1, 9), TEN };
    163 
    164     /**/
    165     private transient int firstNonzeroDigit = -2;
    166 
    167     /** sign field, used for serialization. */
    168     private int signum;
    169 
    170     /** absolute value field, used for serialization */
    171     private byte[] magnitude;
    172 
    173     /** Cache for the hash code. */
    174     private transient int hashCode = 0;
    175 
    176     BigInteger(BigInt a) {
    177         bigInt = a;
    178         bigIntIsValid = true;
    179         validate("BigInteger(BigInt)", "this");
    180         // !oldReprIsValid
    181     }
    182 
    183     BigInteger(int sign, long value) {
    184         bigInt = new BigInt();
    185         bigInt.putULongInt(value, (sign < 0));
    186         bigIntIsValid = true;
    187         // !oldReprIsValid
    188     }
    189 
    190 
    191     /**
    192      * Constructs a number without creating new space. This construct should be
    193      * used only if the three fields of representation are known.
    194      *
    195      * @param sign
    196      *            the sign of the number.
    197      * @param numberLength
    198      *            the length of the internal array.
    199      * @param digits
    200      *            a reference of some array created before.
    201      */
    202     BigInteger(int sign, int numberLength, int[] digits) {
    203         this.sign = sign;
    204         this.numberLength = numberLength;
    205         this.digits = digits;
    206         oldReprIsValid = true;
    207         withNewRepresentation("BigInteger(int sign, int numberLength, int[] digits)");
    208     }
    209 
    210     /**
    211      * Constructs a random non-negative {@code BigInteger} instance in the range
    212      * [0, 2^(numBits)-1].
    213      *
    214      * @param numBits
    215      *            maximum length of the new {@code BigInteger} in bits.
    216      * @param rnd
    217      *            is an optional random generator to be used.
    218      * @throws IllegalArgumentException
    219      *             if {@code numBits} < 0.
    220      */
    221     public BigInteger(int numBits, Random rnd) {
    222         if (numBits < 0) {
    223             // math.1B=numBits must be non-negative
    224             throw new IllegalArgumentException(Messages.getString("math.1B")); //$NON-NLS-1$
    225         }
    226         if (numBits == 0) {
    227             sign = 0;
    228             numberLength = 1;
    229             digits = new int[] { 0 };
    230         } else {
    231             sign = 1;
    232             numberLength = (numBits + 31) >> 5;
    233             digits = new int[numberLength];
    234             for (int i = 0; i < numberLength; i++) {
    235                 digits[i] = rnd.nextInt();
    236             }
    237             // Using only the necessary bits
    238             digits[numberLength - 1] >>>= (-numBits) & 31;
    239             cutOffLeadingZeroes();
    240         }
    241         oldReprIsValid = true;
    242         withNewRepresentation("BigInteger(int numBits, Random rnd)");
    243     }
    244 
    245     /**
    246      * Constructs a random {@code BigInteger} instance in the range [0,
    247      * 2^(bitLength)-1] which is probably prime. The probability that the
    248      * returned {@code BigInteger} is prime is beyond (1-1/2^certainty).
    249      * <p>
    250      * <b>Implementation Note:</b>
    251      * Currently {@code rnd} is ignored. The implementation always uses
    252      * method {@code bn_rand} from the OpenSSL library. {@code bn_rand}
    253      * generates cryptographically strong pseudo-random numbers.
    254      * @see <a href="http://www.openssl.org/docs/crypto/BN_rand.html">
    255      * Specification of random generator used from OpenSSL library</a>
    256      *
    257      * @param bitLength
    258      *            length of the new {@code BigInteger} in bits.
    259      * @param certainty
    260      *            tolerated primality uncertainty.
    261      * @param rnd
    262      *            is an optional random generator to be used.
    263      * @throws ArithmeticException
    264      *             if {@code bitLength} < 2.
    265      */
    266     public BigInteger(int bitLength, int certainty, Random rnd) {
    267         if (bitLength < 2) {
    268             // math.1C=bitLength < 2
    269             throw new ArithmeticException(Messages.getString("math.1C")); //$NON-NLS-1$
    270         }
    271         bigInt = BigInt.generatePrimeDefault(bitLength, rnd, null);
    272         bigIntIsValid = true;
    273         // !oldReprIsValid
    274     }
    275 
    276     /**
    277      * Constructs a new {@code BigInteger} instance from the string
    278      * representation. The string representation consists of an optional minus
    279      * sign followed by a non-empty sequence of decimal digits.
    280      *
    281      * @param val
    282      *            string representation of the new {@code BigInteger}.
    283      * @throws NullPointerException
    284      *             if {@code val == null}.
    285      * @throws NumberFormatException
    286      *             if {@code val} is not a valid representation of a {@code
    287      *             BigInteger}.
    288      */
    289     public BigInteger(String val) {
    290         bigInt = new BigInt();
    291         bigInt.putDecString(val);
    292         bigIntIsValid = true;
    293         // !oldReprIsValid
    294     }
    295 
    296     /**
    297      * Constructs a new {@code BigInteger} instance from the string
    298      * representation. The string representation consists of an optional minus
    299      * sign followed by a non-empty sequence of digits in the specified radix.
    300      * For the conversion the method {@code Character.digit(char, radix)} is
    301      * used.
    302      *
    303      * @param val
    304      *            string representation of the new {@code BigInteger}.
    305      * @param radix
    306      *            the base to be used for the conversion.
    307      * @throws NullPointerException
    308      *             if {@code val == null}.
    309      * @throws NumberFormatException
    310      *             if {@code val} is not a valid representation of a {@code
    311      *             BigInteger} or if {@code radix < Character.MIN_RADIX} or
    312      *             {@code radix > Character.MAX_RADIX}.
    313      */
    314     public BigInteger(String val, int radix) {
    315         if (val == null) {
    316             throw new NullPointerException();
    317         }
    318         if (radix == 10) {
    319             bigInt = new BigInt();
    320             bigInt.putDecString(val);
    321             bigIntIsValid = true;
    322             // !oldReprIsValid
    323         } else if (radix == 16) {
    324             bigInt = new BigInt();
    325             bigInt.putHexString(val);
    326             bigIntIsValid = true;
    327             // !oldReprIsValid
    328         } else {
    329             if ((radix < Character.MIN_RADIX) || (radix > Character.MAX_RADIX)) {
    330                 // math.11=Radix out of range
    331                 throw new NumberFormatException(Messages.getString("math.11")); //$NON-NLS-1$
    332             }
    333             if (val.length() == 0) {
    334                 // math.12=Zero length BigInteger
    335                 throw new NumberFormatException(Messages.getString("math.12")); //$NON-NLS-1$
    336             }
    337             BigInteger.setFromString(this, val, radix);
    338             // oldReprIsValid == true;
    339         }
    340     }
    341 
    342     /**
    343      * Constructs a new {@code BigInteger} instance with the given sign and the
    344      * given magnitude. The sign is given as an integer (-1 for negative, 0 for
    345      * zero, 1 for positive). The magnitude is specified as a byte array. The
    346      * most significant byte is the entry at index 0.
    347      *
    348      * @param signum
    349      *            sign of the new {@code BigInteger} (-1 for negative, 0 for
    350      *            zero, 1 for positive).
    351      * @param magnitude
    352      *            magnitude of the new {@code BigInteger} with the most
    353      *            significant byte first.
    354      * @throws NullPointerException
    355      *             if {@code magnitude == null}.
    356      * @throws NumberFormatException
    357      *             if the sign is not one of -1, 0, 1 or if the sign is zero and
    358      *             the magnitude contains non-zero entries.
    359      */
    360     public BigInteger(int signum, byte[] magnitude) {
    361         if (magnitude == null) {
    362             throw new NullPointerException();
    363         }
    364         if ((signum < -1) || (signum > 1)) {
    365             // math.13=Invalid signum value
    366             throw new NumberFormatException(Messages.getString("math.13")); //$NON-NLS-1$
    367         }
    368         if (signum == 0) {
    369             for (byte element : magnitude) {
    370                 if (element != 0) {
    371                     // math.14=signum-magnitude mismatch
    372                     throw new NumberFormatException(Messages.getString("math.14")); //$NON-NLS-1$
    373                 }
    374             }
    375         }
    376         bigInt = new BigInt();
    377         bigInt.putBigEndian(magnitude, (signum < 0));
    378         bigIntIsValid = true;
    379     }
    380 
    381     /**
    382      * Constructs a new {@code BigInteger} from the given two's complement
    383      * representation. The most significant byte is the entry at index 0. The
    384      * most significant bit of this entry determines the sign of the new {@code
    385      * BigInteger} instance. The given array must not be empty.
    386      *
    387      * @param val
    388      *            two's complement representation of the new {@code BigInteger}.
    389      * @throws NullPointerException
    390      *             if {@code val == null}.
    391      * @throws NumberFormatException
    392      *             if the length of {@code val} is zero.
    393      */
    394     public BigInteger(byte[] val) {
    395         if (val.length == 0) {
    396             // math.12=Zero length BigInteger
    397             throw new NumberFormatException(Messages.getString("math.12")); //$NON-NLS-1$
    398         }
    399         bigInt = new BigInt();
    400         bigInt.putBigEndianTwosComplement(val);
    401         bigIntIsValid = true;
    402     }
    403 
    404 
    405     /**
    406      * Creates a new {@code BigInteger} whose value is equal to the specified
    407      * {@code long} argument.
    408      *
    409      * @param val
    410      *            the value of the new {@code BigInteger}.
    411      * @return {@code BigInteger} instance with the value {@code val}.
    412      */
    413     public static BigInteger valueOf(long val) {
    414         if (val < 0) {
    415             if(val != -1) {
    416                 return new BigInteger(-1, -val);
    417             }
    418             return MINUS_ONE;
    419         } else if (val <= 10) {
    420             return SMALL_VALUES[(int) val];
    421         } else {// (val > 10)
    422             return new BigInteger(1, val);
    423         }
    424     }
    425 
    426     /**
    427      * Returns the two's complement representation of this BigInteger in a byte
    428      * array.
    429      *
    430      * @return two's complement representation of {@code this}.
    431      */
    432     public byte[] toByteArray() {
    433         return twosComplement();
    434     }
    435 
    436     /**
    437      * Returns a (new) {@code BigInteger} whose value is the absolute value of
    438      * {@code this}.
    439      *
    440      * @return {@code abs(this)}.
    441      */
    442     public BigInteger abs() {
    443         validate1("abs()", this);
    444         if (bigInt.sign() >= 0) return this;
    445         else {
    446             BigInt a = bigInt.copy();
    447             a.setSign(1);
    448             return new BigInteger(a);
    449         }
    450     }
    451 
    452     /**
    453      * Returns a new {@code BigInteger} whose value is the {@code -this}.
    454      *
    455      * @return {@code -this}.
    456      */
    457     public BigInteger negate() {
    458         validate1("negate()", this);
    459         int sign = bigInt.sign();
    460         if (sign == 0) return this;
    461         else {
    462             BigInt a = bigInt.copy();
    463             a.setSign(-sign);
    464             return new BigInteger(a);
    465         }
    466     }
    467 
    468     /**
    469      * Returns a new {@code BigInteger} whose value is {@code this + val}.
    470      *
    471      * @param val
    472      *            value to be added to {@code this}.
    473      * @return {@code this + val}.
    474      * @throws NullPointerException
    475      *             if {@code val == null}.
    476      */
    477     public BigInteger add(BigInteger val) {
    478         validate2("add", this, val);
    479         if (val.bigInt.sign() == 0) return this;
    480         if (bigInt.sign() == 0) return val;
    481         return new BigInteger(BigInt.addition(bigInt, val.bigInt));
    482     }
    483 
    484     /**
    485      * Returns a new {@code BigInteger} whose value is {@code this - val}.
    486      *
    487      * @param val
    488      *            value to be subtracted from {@code this}.
    489      * @return {@code this - val}.
    490      * @throws NullPointerException
    491      *             if {@code val == null}.
    492      */
    493     public BigInteger subtract(BigInteger val) {
    494         validate2("subtract", this, val);
    495         if (val.bigInt.sign() == 0) return this;
    496         else return new BigInteger(BigInt.subtraction(bigInt, val.bigInt));
    497     }
    498 
    499     /**
    500      * Returns the sign of this {@code BigInteger}.
    501      *
    502      * @return {@code -1} if {@code this < 0},
    503      *         {@code 0} if {@code this == 0},
    504      *         {@code 1} if {@code this > 0}.
    505      */
    506     public int signum() {
    507      // Optimization to avoid unnecessary duplicate representation:
    508         if (oldReprIsValid) return sign;
    509      // else:
    510         validate1("signum", this);
    511         return bigInt.sign();
    512     }
    513 
    514     /**
    515      * Returns a new {@code BigInteger} whose value is {@code this >> n}. For
    516      * negative arguments, the result is also negative. The shift distance may
    517      * be negative which means that {@code this} is shifted left.
    518      * <p>
    519      * <b>Implementation Note:</b> Usage of this method on negative values is
    520      * not recommended as the current implementation is not efficient.
    521      *
    522      * @param n
    523      *            shift distance
    524      * @return {@code this >> n} if {@code n >= 0}; {@code this << (-n)}
    525      *         otherwise
    526      */
    527     public BigInteger shiftRight(int n) {
    528         return shiftLeft(-n);
    529     }
    530 
    531     /**
    532      * Returns a new {@code BigInteger} whose value is {@code this << n}. The
    533      * result is equivalent to {@code this * 2^n} if n >= 0. The shift distance
    534      * may be negative which means that {@code this} is shifted right. The
    535      * result then corresponds to {@code floor(this / 2^(-n))}.
    536      * <p>
    537      * <b>Implementation Note:</b> Usage of this method on negative values is
    538      * not recommended as the current implementation is not efficient.
    539      *
    540      * @param n
    541      *            shift distance.
    542      * @return {@code this << n} if {@code n >= 0}; {@code this >> (-n)}.
    543      *         otherwise
    544      */
    545     public BigInteger shiftLeft(int n) {
    546         if (n == 0) return this;
    547         int sign = signum();
    548         if (sign == 0) return this;
    549         if ((sign > 0) || (n >= 0)) {
    550             validate1("shiftLeft", this);
    551             return new BigInteger(BigInt.shift(bigInt, n));
    552         }
    553         else {
    554             // Negative numbers faking 2's complement:
    555             // Not worth optimizing this:
    556             // Sticking to Harmony Java implementation.
    557             //
    558             return BitLevel.shiftRight(this, -n);
    559         }
    560     }
    561 
    562     BigInteger shiftLeftOneBit() {
    563         return (signum() == 0) ? this : BitLevel.shiftLeftOneBit(this);
    564     }
    565 
    566     /**
    567      * Returns the length of the value's two's complement representation without
    568      * leading zeros for positive numbers / without leading ones for negative
    569      * values.
    570      * <p>
    571      * The two's complement representation of {@code this} will be at least
    572      * {@code bitLength() + 1} bits long.
    573      * <p>
    574      * The value will fit into an {@code int} if {@code bitLength() < 32} or
    575      * into a {@code long} if {@code bitLength() < 64}.
    576      *
    577      * @return the length of the minimal two's complement representation for
    578      *         {@code this} without the sign bit.
    579      */
    580     public int bitLength() {
    581      // Optimization to avoid unnecessary duplicate representation:
    582         if (!bigIntIsValid && oldReprIsValid) return BitLevel.bitLength(this);
    583      // else:
    584         validate1("bitLength", this);
    585         return bigInt.bitLength();
    586     }
    587 
    588     /**
    589      * Tests whether the bit at position n in {@code this} is set. The result is
    590      * equivalent to {@code this & (2^n) != 0}.
    591      * <p>
    592      * <b>Implementation Note:</b> Usage of this method is not recommended as
    593      * the current implementation is not efficient.
    594      *
    595      * @param n
    596      *            position where the bit in {@code this} has to be inspected.
    597      * @return {@code this & (2^n) != 0}.
    598      * @throws ArithmeticException
    599      *             if {@code n < 0}.
    600      */
    601     public boolean testBit(int n) {
    602         if (n < 0) {
    603             // math.15=Negative bit address
    604             throw new ArithmeticException(Messages.getString("math.15")); //$NON-NLS-1$
    605         }
    606         int sign = signum();
    607         if ((sign > 0) && bigIntIsValid && !oldReprIsValid) {
    608             validate1("testBit", this);
    609             return bigInt.isBitSet(n);
    610         }
    611         else {
    612             // Negative numbers faking 2's complement:
    613             // Not worth optimizing this:
    614             // Sticking to Harmony Java implementation.
    615             //
    616             establishOldRepresentation("testBit");
    617             if (n == 0) {
    618                 return ((digits[0] & 1) != 0);
    619             }
    620             int intCount = n >> 5;
    621             if (intCount >= numberLength) {
    622                 return (sign < 0);
    623             }
    624             int digit = digits[intCount];
    625             n = (1 << (n & 31)); // int with 1 set to the needed position
    626             if (sign < 0) {
    627                 int firstNonZeroDigit = getFirstNonzeroDigit();
    628                 if (  intCount < firstNonZeroDigit  ){
    629                     return false;
    630                 }else if( firstNonZeroDigit == intCount ){
    631                     digit = -digit;
    632                 }else{
    633                     digit = ~digit;
    634                 }
    635             }
    636             return ((digit & n) != 0);
    637         }
    638     }
    639 
    640     /**
    641      * Returns a new {@code BigInteger} which has the same binary representation
    642      * as {@code this} but with the bit at position n set. The result is
    643      * equivalent to {@code this | 2^n}.
    644      * <p>
    645      * <b>Implementation Note:</b> Usage of this method is not recommended as
    646      * the current implementation is not efficient.
    647      *
    648      * @param n
    649      *            position where the bit in {@code this} has to be set.
    650      * @return {@code this | 2^n}.
    651      * @throws ArithmeticException
    652      *             if {@code n < 0}.
    653      */
    654     public BigInteger setBit(int n) {
    655         establishOldRepresentation("setBit");
    656         if( !testBit( n ) ){
    657             return BitLevel.flipBit(this, n);
    658         }else{
    659             return this;
    660         }
    661     }
    662 
    663     /**
    664      * Returns a new {@code BigInteger} which has the same binary representation
    665      * as {@code this} but with the bit at position n cleared. The result is
    666      * equivalent to {@code this & ~(2^n)}.
    667      * <p>
    668      * <b>Implementation Note:</b> Usage of this method is not recommended as
    669      * the current implementation is not efficient.
    670      *
    671      * @param n
    672      *            position where the bit in {@code this} has to be cleared.
    673      * @return {@code this & ~(2^n)}.
    674      * @throws ArithmeticException
    675      *             if {@code n < 0}.
    676      */
    677     public BigInteger clearBit(int n) {
    678         establishOldRepresentation("clearBit");
    679         if (testBit(n)) {
    680             return BitLevel.flipBit(this, n);
    681         } else {
    682             return this;
    683         }
    684     }
    685 
    686     /**
    687      * Returns a new {@code BigInteger} which has the same binary representation
    688      * as {@code this} but with the bit at position n flipped. The result is
    689      * equivalent to {@code this ^ 2^n}.
    690      * <p>
    691      * <b>Implementation Note:</b> Usage of this method is not recommended as
    692      * the current implementation is not efficient.
    693      *
    694      * @param n
    695      *            position where the bit in {@code this} has to be flipped.
    696      * @return {@code this ^ 2^n}.
    697      * @throws ArithmeticException
    698      *             if {@code n < 0}.
    699      */
    700     public BigInteger flipBit(int n) {
    701         establishOldRepresentation("flipBit");
    702         if (n < 0) {
    703             // math.15=Negative bit address
    704             throw new ArithmeticException(Messages.getString("math.15")); //$NON-NLS-1$
    705         }
    706         return BitLevel.flipBit(this, n);
    707     }
    708 
    709     /**
    710      * Returns the position of the lowest set bit in the two's complement
    711      * representation of this {@code BigInteger}. If all bits are zero (this=0)
    712      * then -1 is returned as result.
    713      * <p>
    714      * <b>Implementation Note:</b> Usage of this method is not recommended as
    715      * the current implementation is not efficient.
    716      *
    717      * @return position of lowest bit if {@code this != 0}, {@code -1} otherwise
    718      */
    719     public int getLowestSetBit() {
    720         establishOldRepresentation("getLowestSetBit");
    721         if (sign == 0) {
    722             return -1;
    723         }
    724         // (sign != 0) implies that exists some non zero digit
    725         int i = getFirstNonzeroDigit();
    726         return ((i << 5) + Integer.numberOfTrailingZeros(digits[i]));
    727     }
    728 
    729     /**
    730      * Use {@code bitLength(0)} if you want to know the length of the binary
    731      * value in bits.
    732      * <p>
    733      * Returns the number of bits in the binary representation of {@code this}
    734      * which differ from the sign bit. If {@code this} is positive the result is
    735      * equivalent to the number of bits set in the binary representation of
    736      * {@code this}. If {@code this} is negative the result is equivalent to the
    737      * number of bits set in the binary representation of {@code -this-1}.
    738      * <p>
    739      * <b>Implementation Note:</b> Usage of this method is not recommended as
    740      * the current implementation is not efficient.
    741      *
    742      * @return number of bits in the binary representation of {@code this} which
    743      *         differ from the sign bit
    744      */
    745     public int bitCount() {
    746         establishOldRepresentation("bitCount");
    747         return BitLevel.bitCount(this);
    748     }
    749 
    750     /**
    751      * Returns a new {@code BigInteger} whose value is {@code ~this}. The result
    752      * of this operation is {@code -this-1}.
    753      * <p>
    754      * <b>Implementation Note:</b> Usage of this method is not recommended as
    755      * the current implementation is not efficient.
    756      *
    757      * @return {@code ~this}.
    758      */
    759     public BigInteger not() {
    760         this.establishOldRepresentation("not");
    761         return Logical.not(this).withNewRepresentation("not");
    762     }
    763 
    764     /**
    765      * Returns a new {@code BigInteger} whose value is {@code this & val}.
    766      * <p>
    767      * <b>Implementation Note:</b> Usage of this method is not recommended as
    768      * the current implementation is not efficient.
    769      *
    770      * @param val
    771      *            value to be and'ed with {@code this}.
    772      * @return {@code this & val}.
    773      * @throws NullPointerException
    774      *             if {@code val == null}.
    775      */
    776     public BigInteger and(BigInteger val) {
    777         this.establishOldRepresentation("and1");
    778         val.establishOldRepresentation("and2");
    779         return Logical.and(this, val).withNewRepresentation("and");
    780     }
    781 
    782     /**
    783      * Returns a new {@code BigInteger} whose value is {@code this | val}.
    784      * <p>
    785      * <b>Implementation Note:</b> Usage of this method is not recommended as
    786      * the current implementation is not efficient.
    787      *
    788      * @param val
    789      *            value to be or'ed with {@code this}.
    790      * @return {@code this | val}.
    791      * @throws NullPointerException
    792      *             if {@code val == null}.
    793      */
    794     public BigInteger or(BigInteger val) {
    795         this.establishOldRepresentation("or1");
    796         val.establishOldRepresentation("or2");
    797         return Logical.or(this, val).withNewRepresentation("or");
    798     }
    799 
    800     /**
    801      * Returns a new {@code BigInteger} whose value is {@code this ^ val}.
    802      * <p>
    803      * <b>Implementation Note:</b> Usage of this method is not recommended as
    804      * the current implementation is not efficient.
    805      *
    806      * @param val
    807      *            value to be xor'ed with {@code this}
    808      * @return {@code this ^ val}
    809      * @throws NullPointerException
    810      *             if {@code val == null}
    811      */
    812     public BigInteger xor(BigInteger val) {
    813         this.establishOldRepresentation("xor1");
    814         val.establishOldRepresentation("xor2");
    815         return Logical.xor(this, val).withNewRepresentation("xor");
    816     }
    817 
    818     /**
    819      * Returns a new {@code BigInteger} whose value is {@code this & ~val}.
    820      * Evaluating {@code x.andNot(val)} returns the same result as {@code
    821      * x.and(val.not())}.
    822      * <p>
    823      * <b>Implementation Note:</b> Usage of this method is not recommended as
    824      * the current implementation is not efficient.
    825      *
    826      * @param val
    827      *            value to be not'ed and then and'ed with {@code this}.
    828      * @return {@code this & ~val}.
    829      * @throws NullPointerException
    830      *             if {@code val == null}.
    831      */
    832     public BigInteger andNot(BigInteger val) {
    833         this.establishOldRepresentation("andNot1");
    834         val.establishOldRepresentation("andNot2");
    835         return Logical.andNot(this, val).withNewRepresentation("andNot");
    836     }
    837 
    838     /**
    839      * Returns this {@code BigInteger} as an int value. If {@code this} is too
    840      * big to be represented as an int, then {@code this} % 2^32 is returned.
    841      *
    842      * @return this {@code BigInteger} as an int value.
    843      */
    844     @Override
    845     public int intValue() {
    846         if (bigIntIsValid && (bigInt.twosCompFitsIntoBytes(4))) {
    847             return (int)bigInt.longInt();
    848         }
    849         else {
    850             this.establishOldRepresentation("intValue()");
    851             return (sign * digits[0]);
    852         }
    853     }
    854 
    855     /**
    856      * Returns this {@code BigInteger} as an long value. If {@code this} is too
    857      * big to be represented as an long, then {@code this} % 2^64 is returned.
    858      *
    859      * @return this {@code BigInteger} as a long value.
    860      */
    861     @Override
    862     public long longValue() {
    863         if (bigIntIsValid && (bigInt.twosCompFitsIntoBytes(8))) {
    864             establishOldRepresentation("longValue()");
    865             return bigInt.longInt();
    866         }
    867         else {
    868             establishOldRepresentation("longValue()");
    869             long value = (numberLength > 1) ? (((long) digits[1]) << 32)
    870                     | (digits[0] & 0xFFFFFFFFL) : (digits[0] & 0xFFFFFFFFL);
    871             return (sign * value);
    872         }
    873     }
    874 
    875     /**
    876      * Returns this {@code BigInteger} as an float value. If {@code this} is too
    877      * big to be represented as an float, then {@code Float.POSITIVE_INFINITY}
    878      * or {@code Float.NEGATIVE_INFINITY} is returned. Note, that not all
    879      * integers x in the range [-Float.MAX_VALUE, Float.MAX_VALUE] can be
    880      * represented as a float. The float representation has a mantissa of length
    881      * 24. For example, 2^24+1 = 16777217 is returned as float 16777216.0.
    882      *
    883      * @return this {@code BigInteger} as a float value.
    884      */
    885     @Override
    886     public float floatValue() {
    887         establishOldRepresentation("floatValue()");
    888         return (float) doubleValue();
    889     }
    890 
    891     /**
    892      * Returns this {@code BigInteger} as an double value. If {@code this} is
    893      * too big to be represented as an double, then {@code
    894      * Double.POSITIVE_INFINITY} or {@code Double.NEGATIVE_INFINITY} is
    895      * returned. Note, that not all integers x in the range [-Double.MAX_VALUE,
    896      * Double.MAX_VALUE] can be represented as a double. The double
    897      * representation has a mantissa of length 53. For example, 2^53+1 =
    898      * 9007199254740993 is returned as double 9007199254740992.0.
    899      *
    900      * @return this {@code BigInteger} as a double value
    901      */
    902     @Override
    903     public double doubleValue() {
    904         establishOldRepresentation("doubleValue()");
    905         return Conversion.bigInteger2Double(this);
    906     }
    907 
    908     /**
    909      * Compares this {@code BigInteger} with {@code val}. Returns one of the
    910      * three values 1, 0, or -1.
    911      *
    912      * @param val
    913      *            value to be compared with {@code this}.
    914      * @return {@code 1} if {@code this > val}, {@code -1} if {@code this < val}
    915      *         , {@code 0} if {@code this == val}.
    916      * @throws NullPointerException
    917      *             if {@code val == null}.
    918      */
    919     public int compareTo(BigInteger val) {
    920         validate2("compareTo", this, val);
    921         return BigInt.cmp(bigInt, val.bigInt);
    922     }
    923 
    924     /**
    925      * Returns the minimum of this {@code BigInteger} and {@code val}.
    926      *
    927      * @param val
    928      *            value to be used to compute the minimum with {@code this}.
    929      * @return {@code min(this, val)}.
    930      * @throws NullPointerException
    931      *             if {@code val == null}.
    932      */
    933     public BigInteger min(BigInteger val) {
    934         return ((this.compareTo(val) == -1) ? this : val);
    935     }
    936 
    937     /**
    938      * Returns the maximum of this {@code BigInteger} and {@code val}.
    939      *
    940      * @param val
    941      *            value to be used to compute the maximum with {@code this}
    942      * @return {@code max(this, val)}
    943      * @throws NullPointerException
    944      *             if {@code val == null}
    945      */
    946     public BigInteger max(BigInteger val) {
    947         return ((this.compareTo(val) == 1) ? this : val);
    948     }
    949 
    950     /**
    951      * Returns a hash code for this {@code BigInteger}.
    952      *
    953      * @return hash code for {@code this}.
    954      */
    955     @Override
    956     public int hashCode() {
    957         validate1("hashCode", this);
    958         if (hashCode != 0) {
    959             return hashCode;
    960         }
    961         establishOldRepresentation("hashCode");
    962         for (int i = 0; i < digits.length; i ++) {
    963             hashCode = (int)(hashCode * 33 + (digits[i] & 0xffffffff));
    964         }
    965         hashCode = hashCode * sign;
    966         return hashCode;
    967     }
    968 
    969     /**
    970      * Returns {@code true} if {@code x} is a BigInteger instance and if this
    971      * instance is equal to this {@code BigInteger}.
    972      *
    973      * @param x
    974      *            object to be compared with {@code this}.
    975      * @return true if {@code x} is a BigInteger and {@code this == x},
    976      *          {@code false} otherwise.
    977      */
    978     @Override
    979     public boolean equals(Object x) {
    980         if (this == x) {
    981             return true;
    982         }
    983         if (x instanceof BigInteger) {
    984             return this.compareTo((BigInteger)x) == 0;
    985         }
    986         return false;
    987     }
    988 
    989     /**
    990      * Returns a string representation of this {@code BigInteger} in decimal
    991      * form.
    992      *
    993      * @return a string representation of {@code this} in decimal form.
    994      */
    995     @Override
    996     public String toString() {
    997         validate1("toString()", this);
    998         return bigInt.decString();
    999     }
   1000 
   1001     /**
   1002      * Returns a string containing a string representation of this {@code
   1003      * BigInteger} with base radix. If {@code radix < Character.MIN_RADIX} or
   1004      * {@code radix > Character.MAX_RADIX} then a decimal representation is
   1005      * returned. The characters of the string representation are generated with
   1006      * method {@code Character.forDigit}.
   1007      *
   1008      * @param radix
   1009      *            base to be used for the string representation.
   1010      * @return a string representation of this with radix 10.
   1011      */
   1012     public String toString(int radix) {
   1013         validate1("toString(int radix)", this);
   1014         if (radix == 10) {
   1015             return bigInt.decString();
   1016 //        } else if (radix == 16) {
   1017 //            return bigInt.hexString();
   1018         } else {
   1019             establishOldRepresentation("toString(int radix)");
   1020             return Conversion.bigInteger2String(this, radix);
   1021         }
   1022    }
   1023 
   1024     /**
   1025      * Returns a new {@code BigInteger} whose value is greatest common divisor
   1026      * of {@code this} and {@code val}. If {@code this==0} and {@code val==0}
   1027      * then zero is returned, otherwise the result is positive.
   1028      *
   1029      * @param val
   1030      *            value with which the greatest common divisor is computed.
   1031      * @return {@code gcd(this, val)}.
   1032      * @throws NullPointerException
   1033      *             if {@code val == null}.
   1034      */
   1035     public BigInteger gcd(BigInteger val) {
   1036         validate2("gcd", this, val);
   1037         return new BigInteger(BigInt.gcd(bigInt, val.bigInt, null));
   1038     }
   1039 
   1040     /**
   1041      * Returns a new {@code BigInteger} whose value is {@code this * val}.
   1042      *
   1043      * @param val
   1044      *            value to be multiplied with {@code this}.
   1045      * @return {@code this * val}.
   1046      * @throws NullPointerException
   1047      *             if {@code val == null}.
   1048      */
   1049     public BigInteger multiply(BigInteger val) {
   1050         validate2("multiply", this, val);
   1051         return new BigInteger(BigInt.product(bigInt, val.bigInt, null));
   1052     }
   1053 
   1054     /**
   1055      * Returns a new {@code BigInteger} whose value is {@code this ^ exp}.
   1056      *
   1057      * @param exp
   1058      *            exponent to which {@code this} is raised.
   1059      * @return {@code this ^ exp}.
   1060      * @throws ArithmeticException
   1061      *             if {@code exp < 0}.
   1062      */
   1063     public BigInteger pow(int exp) {
   1064         if (exp < 0) {
   1065             // math.16=Negative exponent
   1066             throw new ArithmeticException(Messages.getString("math.16")); //$NON-NLS-1$
   1067         }
   1068         validate1("pow", this);
   1069         return new BigInteger(BigInt.exp(bigInt, exp, null));
   1070     }
   1071 
   1072     /**
   1073      * Returns a {@code BigInteger} array which contains {@code this / divisor}
   1074      * at index 0 and {@code this % divisor} at index 1.
   1075      *
   1076      * @param divisor
   1077      *            value by which {@code this} is divided.
   1078      * @return {@code [this / divisor, this % divisor]}.
   1079      * @throws NullPointerException
   1080      *             if {@code divisor == null}.
   1081      * @throws ArithmeticException
   1082      *             if {@code divisor == 0}.
   1083      * @see #divide
   1084      * @see #remainder
   1085      */
   1086     public BigInteger[] divideAndRemainder(BigInteger divisor) {
   1087         validate2("divideAndRemainder", this, divisor);
   1088         BigInt quotient = new BigInt();
   1089         BigInt remainder = new BigInt();
   1090         BigInt.division(bigInt, divisor.bigInt, null, quotient, remainder);
   1091         BigInteger[] a = new BigInteger[2];
   1092         a[0] = new BigInteger(quotient);
   1093         a[1] = new BigInteger(remainder);
   1094         a[0].validate("divideAndRemainder", "quotient");
   1095         a[1].validate("divideAndRemainder", "remainder");
   1096         return a;
   1097     }
   1098 
   1099     /**
   1100      * Returns a new {@code BigInteger} whose value is {@code this / divisor}.
   1101      *
   1102      * @param divisor
   1103      *            value by which {@code this} is divided.
   1104      * @return {@code this / divisor}.
   1105      * @throws NullPointerException
   1106      *             if {@code divisor == null}.
   1107      * @throws ArithmeticException
   1108      *             if {@code divisor == 0}.
   1109      */
   1110     public BigInteger divide(BigInteger divisor) {
   1111         validate2("divide", this, divisor);
   1112         BigInt quotient = new BigInt();
   1113         BigInt.division(bigInt, divisor.bigInt, null, quotient, null);
   1114         return new BigInteger(quotient);
   1115     }
   1116 
   1117     /**
   1118      * Returns a new {@code BigInteger} whose value is {@code this % divisor}.
   1119      * Regarding signs this methods has the same behavior as the % operator on
   1120      * int's, i.e. the sign of the remainder is the same as the sign of this.
   1121      *
   1122      * @param divisor
   1123      *            value by which {@code this} is divided.
   1124      * @return {@code this % divisor}.
   1125      * @throws NullPointerException
   1126      *             if {@code divisor == null}.
   1127      * @throws ArithmeticException
   1128      *             if {@code divisor == 0}.
   1129      */
   1130     public BigInteger remainder(BigInteger divisor) {
   1131         validate2("remainder", this, divisor);
   1132         BigInt remainder = new BigInt();
   1133         BigInt.division(bigInt, divisor.bigInt, null, null, remainder);
   1134         return new BigInteger(remainder);
   1135     }
   1136 
   1137     /**
   1138      * Returns a new {@code BigInteger} whose value is {@code 1/this mod m}. The
   1139      * modulus {@code m} must be positive. The result is guaranteed to be in the
   1140      * interval {@code [0, m)} (0 inclusive, m exclusive). If {@code this} is
   1141      * not relatively prime to m, then an exception is thrown.
   1142      *
   1143      * @param m
   1144      *            the modulus.
   1145      * @return {@code 1/this mod m}.
   1146      * @throws NullPointerException
   1147      *             if {@code m == null}
   1148      * @throws ArithmeticException
   1149      *             if {@code m < 0 or} if {@code this} is not relatively prime
   1150      *             to {@code m}
   1151      */
   1152     public BigInteger modInverse(BigInteger m) {
   1153         if (m.signum() <= 0) {
   1154             // math.18=BigInteger: modulus not positive
   1155             throw new ArithmeticException(Messages.getString("math.18")); //$NON-NLS-1$
   1156         }
   1157         validate2("modInverse", this, m);
   1158         return new BigInteger(BigInt.modInverse(bigInt, m.bigInt, null));
   1159     }
   1160 
   1161     /**
   1162      * Returns a new {@code BigInteger} whose value is {@code this^exponent mod
   1163      * m}. The modulus {@code m} must be positive. The result is guaranteed to
   1164      * be in the interval {@code [0, m)} (0 inclusive, m exclusive). If the
   1165      * exponent is negative, then {@code this.modInverse(m)^(-exponent) mod m)}
   1166      * is computed. The inverse of this only exists if {@code this} is
   1167      * relatively prime to m, otherwise an exception is thrown.
   1168      *
   1169      * @param exponent
   1170      *            the exponent.
   1171      * @param m
   1172      *            the modulus.
   1173      * @return {@code this^exponent mod val}.
   1174      * @throws NullPointerException
   1175      *             if {@code m == null} or {@code exponent == null}.
   1176      * @throws ArithmeticException
   1177      *             if {@code m < 0} or if {@code exponent<0} and this is not
   1178      *             relatively prime to {@code m}.
   1179      */
   1180     public BigInteger modPow(BigInteger exponent, BigInteger m) {
   1181         if (m.signum() <= 0) {
   1182             // math.18=BigInteger: modulus not positive
   1183             throw new ArithmeticException(Messages.getString("math.18")); //$NON-NLS-1$
   1184         }
   1185         BigInteger base;
   1186         if (exponent.signum() < 0) {
   1187             base = modInverse(m);
   1188 //            exponent = exponent.negate(); // Not needed as sign is ignored anyway!
   1189         } else {
   1190             base = this;
   1191         }
   1192         validate3("modPow", base, exponent, m);
   1193         return new BigInteger(BigInt.modExp(base.bigInt, exponent.bigInt, m.bigInt, null));
   1194     }
   1195 
   1196     /**
   1197      * Returns a new {@code BigInteger} whose value is {@code this mod m}. The
   1198      * modulus {@code m} must be positive. The result is guaranteed to be in the
   1199      * interval {@code [0, m)} (0 inclusive, m exclusive). The behavior of this
   1200      * function is not equivalent to the behavior of the % operator defined for
   1201      * the built-in {@code int}'s.
   1202      *
   1203      * @param m
   1204      *            the modulus.
   1205      * @return {@code this mod m}.
   1206      * @throws NullPointerException
   1207      *             if {@code m == null}.
   1208      * @throws ArithmeticException
   1209      *             if {@code m < 0}.
   1210      */
   1211     public BigInteger mod(BigInteger m) {
   1212         if (m.signum() <= 0) {
   1213             // math.18=BigInteger: modulus not positive
   1214             throw new ArithmeticException(Messages.getString("math.18")); //$NON-NLS-1$
   1215         }
   1216         validate2("mod", this, m);
   1217         return new BigInteger(BigInt.modulus(bigInt, m.bigInt, null));
   1218     }
   1219 
   1220     /**
   1221      * Tests whether this {@code BigInteger} is probably prime. If {@code true}
   1222      * is returned, then this is prime with a probability beyond
   1223      * (1-1/2^certainty). If {@code false} is returned, then this is definitely
   1224      * composite. If the argument {@code certainty} <= 0, then this method
   1225      * returns true.
   1226      *
   1227      * @param certainty
   1228      *            tolerated primality uncertainty.
   1229      * @return {@code true}, if {@code this} is probably prime, {@code false}
   1230      *         otherwise.
   1231      */
   1232     public boolean isProbablePrime(int certainty) {
   1233         validate1("isProbablePrime", this);
   1234         return bigInt.isPrime(certainty, null, null);
   1235     }
   1236 
   1237     /**
   1238      * Returns the smallest integer x > {@code this} which is probably prime as
   1239      * a {@code BigInteger} instance. The probability that the returned {@code
   1240      * BigInteger} is prime is beyond (1-1/2^80).
   1241      *
   1242      * @return smallest integer > {@code this} which is robably prime.
   1243      * @throws ArithmeticException
   1244      *             if {@code this < 0}.
   1245      */
   1246     public BigInteger nextProbablePrime() {
   1247         if (sign < 0) {
   1248             // math.1A=start < 0: {0}
   1249             throw new ArithmeticException(Messages.getString("math.1A", this)); //$NON-NLS-1$
   1250         }
   1251         return Primality.nextProbablePrime(this);
   1252     }
   1253 
   1254     /**
   1255      * Returns a random positive {@code BigInteger} instance in the range [0,
   1256      * 2^(bitLength)-1] which is probably prime. The probability that the
   1257      * returned {@code BigInteger} is prime is beyond (1-1/2^80).
   1258      * <p>
   1259      * <b>Implementation Note:</b> Currently {@code rnd} is ignored.
   1260      *
   1261      * @param bitLength
   1262      *            length of the new {@code BigInteger} in bits.
   1263      * @param rnd
   1264      *            random generator used to generate the new {@code BigInteger}.
   1265      * @return probably prime random {@code BigInteger} instance.
   1266      * @throws IllegalArgumentException
   1267      *             if {@code bitLength < 2}.
   1268      */
   1269     public static BigInteger probablePrime(int bitLength, Random rnd) {
   1270         return new BigInteger(bitLength, 100, rnd);
   1271     }
   1272 
   1273     /* Private Methods */
   1274 
   1275     /**
   1276      * Returns the two's complement representation of this BigInteger in a byte
   1277      * array.
   1278      *
   1279      * @return two's complement representation of {@code this}
   1280      */
   1281     private byte[] twosComplement() {
   1282         establishOldRepresentation("twosComplement()");
   1283         if( this.sign == 0 ){
   1284             return new byte[]{0};
   1285         }
   1286         BigInteger temp = this;
   1287         int bitLen = bitLength();
   1288         int iThis = getFirstNonzeroDigit();
   1289         int bytesLen = (bitLen >> 3) + 1;
   1290         /* Puts the little-endian int array representing the magnitude
   1291          * of this BigInteger into the big-endian byte array. */
   1292         byte[] bytes = new byte[bytesLen];
   1293         int firstByteNumber = 0;
   1294         int highBytes;
   1295         int digitIndex = 0;
   1296         int bytesInInteger = 4;
   1297         int digit;
   1298         int hB;
   1299 
   1300         if (bytesLen - (numberLength << 2) == 1) {
   1301             bytes[0] = (byte) ((sign < 0) ? -1 : 0);
   1302             highBytes = 4;
   1303             firstByteNumber++;
   1304         } else {
   1305             hB = bytesLen & 3;
   1306             highBytes = (hB == 0) ? 4 : hB;
   1307         }
   1308 
   1309         digitIndex = iThis;
   1310         bytesLen -= iThis << 2;
   1311 
   1312         if (sign < 0) {
   1313             digit = -temp.digits[digitIndex];
   1314             digitIndex++;
   1315             if(digitIndex == numberLength){
   1316                 bytesInInteger = highBytes;
   1317             }
   1318             for (int i = 0; i < bytesInInteger; i++, digit >>= 8) {
   1319                 bytes[--bytesLen] = (byte) digit;
   1320             }
   1321             while( bytesLen > firstByteNumber ){
   1322                 digit = ~temp.digits[digitIndex];
   1323                 digitIndex++;
   1324                 if(digitIndex == numberLength){
   1325                     bytesInInteger = highBytes;
   1326                 }
   1327                 for (int i = 0; i < bytesInInteger; i++, digit >>= 8) {
   1328                     bytes[--bytesLen] = (byte) digit;
   1329                 }
   1330             }
   1331         } else {
   1332             while (bytesLen > firstByteNumber) {
   1333                 digit = temp.digits[digitIndex];
   1334                 digitIndex++;
   1335                 if (digitIndex == numberLength) {
   1336                     bytesInInteger = highBytes;
   1337                 }
   1338                 for (int i = 0; i < bytesInInteger; i++, digit >>= 8) {
   1339                     bytes[--bytesLen] = (byte) digit;
   1340                 }
   1341             }
   1342         }
   1343         return bytes;
   1344     }
   1345 
   1346 
   1347     static int multiplyByInt(int res[], int a[], final int aSize, final int factor) {
   1348         long carry = 0;
   1349 
   1350         for (int i = 0; i < aSize; i++) {
   1351             carry += (a[i] & 0xFFFFFFFFL) * (factor & 0xFFFFFFFFL);
   1352             res[i] = (int)carry;
   1353             carry >>>= 32;
   1354         }
   1355         return (int)carry;
   1356     }
   1357 
   1358     static int inplaceAdd(int a[], final int aSize, final int addend) {
   1359         long carry = addend & 0xFFFFFFFFL;
   1360 
   1361         for (int i = 0; (carry != 0) && (i < aSize); i++) {
   1362             carry += a[i] & 0xFFFFFFFFL;
   1363             a[i] = (int) carry;
   1364             carry >>= 32;
   1365         }
   1366         return (int) carry;
   1367     }
   1368 
   1369     /** @see BigInteger#BigInteger(String, int) */
   1370     private static void setFromString(BigInteger bi, String val, int radix) {
   1371         int sign;
   1372         int[] digits;
   1373         int numberLength;
   1374         int stringLength = val.length();
   1375         int startChar;
   1376         int endChar = stringLength;
   1377 
   1378         if (val.charAt(0) == '-') {
   1379             sign = -1;
   1380             startChar = 1;
   1381             stringLength--;
   1382         } else {
   1383             sign = 1;
   1384             startChar = 0;
   1385         }
   1386         /*
   1387          * We use the following algorithm: split a string into portions of n
   1388          * characters and convert each portion to an integer according to the
   1389          * radix. Then convert an exp(radix, n) based number to binary using the
   1390          * multiplication method. See D. Knuth, The Art of Computer Programming,
   1391          * vol. 2.
   1392          */
   1393 
   1394         int charsPerInt = Conversion.digitFitInInt[radix];
   1395         int bigRadixDigitsLength = stringLength / charsPerInt;
   1396         int topChars = stringLength % charsPerInt;
   1397 
   1398         if (topChars != 0) {
   1399             bigRadixDigitsLength++;
   1400         }
   1401         digits = new int[bigRadixDigitsLength];
   1402         // Get the maximal power of radix that fits in int
   1403         int bigRadix = Conversion.bigRadices[radix - 2];
   1404         // Parse an input string and accumulate the BigInteger's magnitude
   1405         int digitIndex = 0; // index of digits array
   1406         int substrEnd = startChar + ((topChars == 0) ? charsPerInt : topChars);
   1407         int newDigit;
   1408 
   1409         for (int substrStart = startChar; substrStart < endChar; substrStart = substrEnd, substrEnd = substrStart
   1410                 + charsPerInt) {
   1411             int bigRadixDigit = Integer.parseInt(val.substring(substrStart,
   1412                     substrEnd), radix);
   1413             newDigit = multiplyByInt(digits, digits, digitIndex, bigRadix);
   1414             newDigit += inplaceAdd(digits, digitIndex, bigRadixDigit);
   1415             digits[digitIndex++] = newDigit;
   1416         }
   1417         numberLength = digitIndex;
   1418         bi.sign = sign;
   1419         bi.numberLength = numberLength;
   1420         bi.digits = digits;
   1421         bi.cutOffLeadingZeroes();
   1422         bi.oldReprIsValid = true;
   1423         bi.withNewRepresentation("Cordoba-BigInteger: private static setFromString");
   1424     }
   1425 
   1426 
   1427     /** Decreases {@code numberLength} if there are zero high elements. */
   1428     final void cutOffLeadingZeroes() {
   1429         while ((numberLength > 0) && (digits[--numberLength] == 0)) {
   1430             ;
   1431         }
   1432         if (digits[numberLength++] == 0) {
   1433             sign = 0;
   1434         }
   1435     }
   1436 
   1437     /** Tests if {@code this.abs()} is equals to {@code ONE} */
   1438     boolean isOne() {
   1439 //        System.out.println("isOne");
   1440         return ((numberLength == 1) && (digits[0] == 1));
   1441     }
   1442 
   1443 
   1444     int getFirstNonzeroDigit(){
   1445 //        validate1("Cordoba-BigInteger: getFirstNonzeroDigit", this);
   1446         if( firstNonzeroDigit == -2 ){
   1447             int i;
   1448             if( this.sign == 0  ){
   1449                 i = -1;
   1450             } else{
   1451                 for(i=0; digits[i]==0; i++)
   1452                     ;
   1453             }
   1454             firstNonzeroDigit = i;
   1455         }
   1456         return firstNonzeroDigit;
   1457     }
   1458 
   1459     /*
   1460      * Returns a copy of the current instance to achieve immutability
   1461      */
   1462 // Only used by Primality.nextProbablePrime()
   1463     BigInteger copy() {
   1464         establishOldRepresentation("copy()");
   1465         int[] copyDigits = new int[numberLength];
   1466         System.arraycopy(digits, 0, copyDigits, 0, numberLength);
   1467         return new BigInteger(sign, numberLength, copyDigits);
   1468     }
   1469 
   1470     /**
   1471      * Assignes all transient fields upon deserialization of a
   1472      * {@code BigInteger} instance.
   1473      */
   1474     private void readObject(ObjectInputStream in) throws IOException,
   1475             ClassNotFoundException {
   1476         in.defaultReadObject();
   1477         bigInt = new BigInt();
   1478         bigInt.putBigEndian(magnitude, (signum < 0));
   1479         bigIntIsValid = true;
   1480         // !oldReprIsValid
   1481     }
   1482 
   1483     /**
   1484      * Prepares this {@code BigInteger} for serialization, i.e. the
   1485      * non-transient fields {@code signum} and {@code magnitude} are assigned.
   1486      */
   1487     private void writeObject(ObjectOutputStream out) throws IOException {
   1488         validate("writeObject", "this");
   1489         signum = bigInt.sign();
   1490 //        if (magnitude == null)
   1491             magnitude = bigInt.bigEndianMagnitude();
   1492         out.defaultWriteObject();
   1493     }
   1494 
   1495 
   1496     void unCache(){
   1497         firstNonzeroDigit = -2;
   1498     }
   1499 }
   1500