< prev index next >

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

Print this page




  99  * <p>All methods and constructors in this class throw
 100  * {@code NullPointerException} when passed
 101  * a null object reference for any input parameter.
 102  *
 103  * BigInteger must support values in the range
 104  * -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to
 105  * +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive)
 106  * and may support values outside of that range.
 107  *
 108  * The range of probable prime values is limited and may be less than
 109  * the full supported positive range of {@code BigInteger}.
 110  * The range must be at least 1 to 2<sup>500000000</sup>.
 111  *
 112  * @implNote
 113  * BigInteger constructors and operations throw {@code ArithmeticException} when
 114  * the result is out of the supported range of
 115  * -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to
 116  * +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive).
 117  *
 118  * @see     BigDecimal

 119  * @author  Josh Bloch
 120  * @author  Michael McCloskey
 121  * @author  Alan Eliasen
 122  * @author  Timothy Buktu
 123  * @since 1.1
 124  */
 125 
 126 public class BigInteger extends Number implements Comparable<BigInteger> {
 127     /**
 128      * The signum of this BigInteger: -1 for negative, 0 for zero, or
 129      * 1 for positive.  Note that the BigInteger zero <i>must</i> have
 130      * a signum of 0.  This is necessary to ensures that there is exactly one
 131      * representation for each BigInteger value.
 132      */
 133     final int signum;
 134 
 135     /**
 136      * The magnitude of this BigInteger, in <i>big-endian</i> order: the
 137      * zeroth element of this array is the most-significant int of the
 138      * magnitude.  The magnitude must be "minimal" in that the most-significant
 139      * int ({@code mag[0]}) must be non-zero.  This is necessary to
 140      * ensure that there is exactly one representation for each BigInteger
 141      * value.  Note that this implies that the BigInteger zero has a
 142      * zero-length mag array.
 143      */
 144     final int[] mag;
 145 
 146     // The following fields are stable variables. A stable variable's value
 147     // changes at most once from the default zero value to a non-zero stable
 148     // value. A stable value is calculated lazily on demand.
 149 


 693 
 694     private static byte[] randomBits(int numBits, Random rnd) {
 695         if (numBits < 0)
 696             throw new IllegalArgumentException("numBits must be non-negative");
 697         int numBytes = (int)(((long)numBits+7)/8); // avoid overflow
 698         byte[] randomBits = new byte[numBytes];
 699 
 700         // Generate random bytes and mask out any excess bits
 701         if (numBytes > 0) {
 702             rnd.nextBytes(randomBits);
 703             int excessBits = 8*numBytes - numBits;
 704             randomBits[0] &= (1 << (8-excessBits)) - 1;
 705         }
 706         return randomBits;
 707     }
 708 
 709     /**
 710      * Constructs a randomly generated positive BigInteger that is probably
 711      * prime, with the specified bitLength.
 712      *
 713      * <p>It is recommended that the {@link #probablePrime probablePrime}
 714      * method be used in preference to this constructor unless there
 715      * is a compelling need to specify a certainty.
 716      *
 717      * @param  bitLength bitLength of the returned BigInteger.
 718      * @param  certainty a measure of the uncertainty that the caller is
 719      *         willing to tolerate.  The probability that the new BigInteger
 720      *         represents a prime number will exceed
 721      *         (1 - 1/2<sup>{@code certainty}</sup>).  The execution time of
 722      *         this constructor is proportional to the value of this parameter.
 723      * @param  rnd source of random bits used to select candidates to be
 724      *         tested for primality.
 725      * @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large.
 726      * @see    #bitLength()
 727      */
 728     public BigInteger(int bitLength, int certainty, Random rnd) {
 729         BigInteger prime;
 730 
 731         if (bitLength < 2)
 732             throw new ArithmeticException("bitLength < 2");
 733         prime = (bitLength < SMALL_PRIME_THRESHOLD


1140     /**
1141      * Throws an {@code ArithmeticException} if the {@code BigInteger} would be
1142      * out of the supported range.
1143      *
1144      * @throws ArithmeticException if {@code this} exceeds the supported range.
1145      */
1146     private void checkRange() {
1147         if (mag.length > MAX_MAG_LENGTH || mag.length == MAX_MAG_LENGTH && mag[0] < 0) {
1148             reportOverflow();
1149         }
1150     }
1151 
1152     private static void reportOverflow() {
1153         throw new ArithmeticException("BigInteger would overflow supported range");
1154     }
1155 
1156     //Static Factory Methods
1157 
1158     /**
1159      * Returns a BigInteger whose value is equal to that of the
1160      * specified {@code long}.  This "static factory method" is
1161      * provided in preference to a ({@code long}) constructor
1162      * because it allows for reuse of frequently used BigIntegers.


1163      *
1164      * @param  val value of the BigInteger to return.
1165      * @return a BigInteger with the specified value.
1166      */
1167     public static BigInteger valueOf(long val) {
1168         // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
1169         if (val == 0)
1170             return ZERO;
1171         if (val > 0 && val <= MAX_CONSTANT)
1172             return posConst[(int) val];
1173         else if (val < 0 && val >= -MAX_CONSTANT)
1174             return negConst[(int) -val];
1175 
1176         return new BigInteger(val);
1177     }
1178 
1179     /**
1180      * Constructs a BigInteger with the specified value, which may not be zero.
1181      */
1182     private BigInteger(long val) {


3534             lsb = 0;
3535             if (signum == 0) {
3536                 lsb -= 1;
3537             } else {
3538                 // Search for lowest order nonzero int
3539                 int i,b;
3540                 for (i=0; (b = getInt(i)) == 0; i++)
3541                     ;
3542                 lsb += (i << 5) + Integer.numberOfTrailingZeros(b);
3543             }
3544             lowestSetBitPlusTwo = lsb + 2;
3545         }
3546         return lsb;
3547     }
3548 
3549 
3550     // Miscellaneous Bit Operations
3551 
3552     /**
3553      * Returns the number of bits in the minimal two's-complement
3554      * representation of this BigInteger, <i>excluding</i> a sign bit.
3555      * For positive BigIntegers, this is equivalent to the number of bits in
3556      * the ordinary binary representation.  (Computes
3557      * {@code (ceil(log2(this < 0 ? -this : this+1)))}.)
3558      *
3559      * @return number of bits in the minimal two's-complement
3560      *         representation of this BigInteger, <i>excluding</i> a sign bit.
3561      */
3562     public int bitLength() {
3563         int n = bitLengthPlusOne - 1;
3564         if (n == -1) { // bitLength not initialized yet
3565             int[] m = mag;
3566             int len = m.length;
3567             if (len == 0) {
3568                 n = 0; // offset by one to initialize
3569             }  else {
3570                 // Calculate the bit length of the magnitude
3571                 int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]);
3572                  if (signum < 0) {
3573                      // Check if magnitude is a power of two
3574                      boolean pow2 = (Integer.bitCount(mag[0]) == 1);
3575                      for (int i=1; i< len && pow2; i++)
3576                          pow2 = (mag[i] == 0);
3577 
3578                      n = (pow2 ? magBitLength -1 : magBitLength);
3579                  } else {
3580                      n = magBitLength;


4017         int byteLen = bitLength()/8 + 1;
4018         byte[] byteArray = new byte[byteLen];
4019 
4020         for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i >= 0; i--) {
4021             if (bytesCopied == 4) {
4022                 nextInt = getInt(intIndex++);
4023                 bytesCopied = 1;
4024             } else {
4025                 nextInt >>>= 8;
4026                 bytesCopied++;
4027             }
4028             byteArray[i] = (byte)nextInt;
4029         }
4030         return byteArray;
4031     }
4032 
4033     /**
4034      * Converts this BigInteger to an {@code int}.  This
4035      * conversion is analogous to a
4036      * <i>narrowing primitive conversion</i> from {@code long} to
4037      * {@code int} as defined in section 5.1.3 of
4038      * <cite>The Java&trade; Language Specification</cite>:
4039      * if this BigInteger is too big to fit in an
4040      * {@code int}, only the low-order 32 bits are returned.
4041      * Note that this conversion can lose information about the
4042      * overall magnitude of the BigInteger value as well as return a
4043      * result with the opposite sign.
4044      *
4045      * @return this BigInteger converted to an {@code int}.
4046      * @see #intValueExact()

4047      */
4048     public int intValue() {
4049         int result = 0;
4050         result = getInt(0);
4051         return result;
4052     }
4053 
4054     /**
4055      * Converts this BigInteger to a {@code long}.  This
4056      * conversion is analogous to a
4057      * <i>narrowing primitive conversion</i> from {@code long} to
4058      * {@code int} as defined in section 5.1.3 of
4059      * <cite>The Java&trade; Language Specification</cite>:
4060      * if this BigInteger is too big to fit in a
4061      * {@code long}, only the low-order 64 bits are returned.
4062      * Note that this conversion can lose information about the
4063      * overall magnitude of the BigInteger value as well as return a
4064      * result with the opposite sign.
4065      *
4066      * @return this BigInteger converted to a {@code long}.
4067      * @see #longValueExact()

4068      */
4069     public long longValue() {
4070         long result = 0;
4071 
4072         for (int i=1; i >= 0; i--)
4073             result = (result << 32) + (getInt(i) & LONG_MASK);
4074         return result;
4075     }
4076 
4077     /**
4078      * Converts this BigInteger to a {@code float}.  This
4079      * conversion is similar to the
4080      * <i>narrowing primitive conversion</i> from {@code double} to
4081      * {@code float} as defined in section 5.1.3 of
4082      * <cite>The Java&trade; Language Specification</cite>:
4083      * if this BigInteger has too great a magnitude
4084      * to represent as a {@code float}, it will be converted to
4085      * {@link Float#NEGATIVE_INFINITY} or {@link
4086      * Float#POSITIVE_INFINITY} as appropriate.  Note that even when
4087      * the return value is finite, this conversion can lose
4088      * information about the precision of the BigInteger value.
4089      *
4090      * @return this BigInteger converted to a {@code float}.

4091      */
4092     public float floatValue() {
4093         if (signum == 0) {
4094             return 0.0f;
4095         }
4096 
4097         int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;
4098 
4099         // exponent == floor(log2(abs(this)))
4100         if (exponent < Long.SIZE - 1) {
4101             return longValue();
4102         } else if (exponent > Float.MAX_EXPONENT) {
4103             return signum > 0 ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;
4104         }
4105 
4106         /*
4107          * We need the top SIGNIFICAND_WIDTH bits, including the "implicit"
4108          * one bit. To make rounding easier, we pick out the top
4109          * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or
4110          * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1


4145                 && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);
4146         int signifRounded = increment ? signifFloor + 1 : signifFloor;
4147         int bits = ((exponent + FloatConsts.EXP_BIAS))
4148                 << (FloatConsts.SIGNIFICAND_WIDTH - 1);
4149         bits += signifRounded;
4150         /*
4151          * If signifRounded == 2^24, we'd need to set all of the significand
4152          * bits to zero and add 1 to the exponent. This is exactly the behavior
4153          * we get from just adding signifRounded to bits directly. If the
4154          * exponent is Float.MAX_EXPONENT, we round up (correctly) to
4155          * Float.POSITIVE_INFINITY.
4156          */
4157         bits |= signum & FloatConsts.SIGN_BIT_MASK;
4158         return Float.intBitsToFloat(bits);
4159     }
4160 
4161     /**
4162      * Converts this BigInteger to a {@code double}.  This
4163      * conversion is similar to the
4164      * <i>narrowing primitive conversion</i> from {@code double} to
4165      * {@code float} as defined in section 5.1.3 of
4166      * <cite>The Java&trade; Language Specification</cite>:
4167      * if this BigInteger has too great a magnitude
4168      * to represent as a {@code double}, it will be converted to
4169      * {@link Double#NEGATIVE_INFINITY} or {@link
4170      * Double#POSITIVE_INFINITY} as appropriate.  Note that even when
4171      * the return value is finite, this conversion can lose
4172      * information about the precision of the BigInteger value.
4173      *
4174      * @return this BigInteger converted to a {@code double}.

4175      */
4176     public double doubleValue() {
4177         if (signum == 0) {
4178             return 0.0;
4179         }
4180 
4181         int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;
4182 
4183         // exponent == floor(log2(abs(this))Double)
4184         if (exponent < Long.SIZE - 1) {
4185             return longValue();
4186         } else if (exponent > Double.MAX_EXPONENT) {
4187             return signum > 0 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
4188         }
4189 
4190         /*
4191          * We need the top SIGNIFICAND_WIDTH bits, including the "implicit"
4192          * one bit. To make rounding easier, we pick out the top
4193          * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or
4194          * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1




  99  * <p>All methods and constructors in this class throw
 100  * {@code NullPointerException} when passed
 101  * a null object reference for any input parameter.
 102  *
 103  * BigInteger must support values in the range
 104  * -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to
 105  * +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive)
 106  * and may support values outside of that range.
 107  *
 108  * The range of probable prime values is limited and may be less than
 109  * the full supported positive range of {@code BigInteger}.
 110  * The range must be at least 1 to 2<sup>500000000</sup>.
 111  *
 112  * @implNote
 113  * BigInteger constructors and operations throw {@code ArithmeticException} when
 114  * the result is out of the supported range of
 115  * -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to
 116  * +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive).
 117  *
 118  * @see     BigDecimal
 119  * @jls     4.2.2 Integer Operations
 120  * @author  Josh Bloch
 121  * @author  Michael McCloskey
 122  * @author  Alan Eliasen
 123  * @author  Timothy Buktu
 124  * @since 1.1
 125  */
 126 
 127 public class BigInteger extends Number implements Comparable<BigInteger> {
 128     /**
 129      * The signum of this BigInteger: -1 for negative, 0 for zero, or
 130      * 1 for positive.  Note that the BigInteger zero <em>must</em> have
 131      * a signum of 0.  This is necessary to ensures that there is exactly one
 132      * representation for each BigInteger value.
 133      */
 134     final int signum;
 135 
 136     /**
 137      * The magnitude of this BigInteger, in <i>big-endian</i> order: the
 138      * zeroth element of this array is the most-significant int of the
 139      * magnitude.  The magnitude must be "minimal" in that the most-significant
 140      * int ({@code mag[0]}) must be non-zero.  This is necessary to
 141      * ensure that there is exactly one representation for each BigInteger
 142      * value.  Note that this implies that the BigInteger zero has a
 143      * zero-length mag array.
 144      */
 145     final int[] mag;
 146 
 147     // The following fields are stable variables. A stable variable's value
 148     // changes at most once from the default zero value to a non-zero stable
 149     // value. A stable value is calculated lazily on demand.
 150 


 694 
 695     private static byte[] randomBits(int numBits, Random rnd) {
 696         if (numBits < 0)
 697             throw new IllegalArgumentException("numBits must be non-negative");
 698         int numBytes = (int)(((long)numBits+7)/8); // avoid overflow
 699         byte[] randomBits = new byte[numBytes];
 700 
 701         // Generate random bytes and mask out any excess bits
 702         if (numBytes > 0) {
 703             rnd.nextBytes(randomBits);
 704             int excessBits = 8*numBytes - numBits;
 705             randomBits[0] &= (1 << (8-excessBits)) - 1;
 706         }
 707         return randomBits;
 708     }
 709 
 710     /**
 711      * Constructs a randomly generated positive BigInteger that is probably
 712      * prime, with the specified bitLength.
 713      *
 714      * @apiNote It is recommended that the {@link #probablePrime probablePrime}
 715      * method be used in preference to this constructor unless there
 716      * is a compelling need to specify a certainty.
 717      *
 718      * @param  bitLength bitLength of the returned BigInteger.
 719      * @param  certainty a measure of the uncertainty that the caller is
 720      *         willing to tolerate.  The probability that the new BigInteger
 721      *         represents a prime number will exceed
 722      *         (1 - 1/2<sup>{@code certainty}</sup>).  The execution time of
 723      *         this constructor is proportional to the value of this parameter.
 724      * @param  rnd source of random bits used to select candidates to be
 725      *         tested for primality.
 726      * @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large.
 727      * @see    #bitLength()
 728      */
 729     public BigInteger(int bitLength, int certainty, Random rnd) {
 730         BigInteger prime;
 731 
 732         if (bitLength < 2)
 733             throw new ArithmeticException("bitLength < 2");
 734         prime = (bitLength < SMALL_PRIME_THRESHOLD


1141     /**
1142      * Throws an {@code ArithmeticException} if the {@code BigInteger} would be
1143      * out of the supported range.
1144      *
1145      * @throws ArithmeticException if {@code this} exceeds the supported range.
1146      */
1147     private void checkRange() {
1148         if (mag.length > MAX_MAG_LENGTH || mag.length == MAX_MAG_LENGTH && mag[0] < 0) {
1149             reportOverflow();
1150         }
1151     }
1152 
1153     private static void reportOverflow() {
1154         throw new ArithmeticException("BigInteger would overflow supported range");
1155     }
1156 
1157     //Static Factory Methods
1158 
1159     /**
1160      * Returns a BigInteger whose value is equal to that of the
1161      * specified {@code long}.
1162      *
1163      * @apiNote This static factory method is provided in preference
1164      * to a ({@code long}) constructor because it allows for reuse of
1165      * frequently used BigIntegers.
1166      *
1167      * @param  val value of the BigInteger to return.
1168      * @return a BigInteger with the specified value.
1169      */
1170     public static BigInteger valueOf(long val) {
1171         // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
1172         if (val == 0)
1173             return ZERO;
1174         if (val > 0 && val <= MAX_CONSTANT)
1175             return posConst[(int) val];
1176         else if (val < 0 && val >= -MAX_CONSTANT)
1177             return negConst[(int) -val];
1178 
1179         return new BigInteger(val);
1180     }
1181 
1182     /**
1183      * Constructs a BigInteger with the specified value, which may not be zero.
1184      */
1185     private BigInteger(long val) {


3537             lsb = 0;
3538             if (signum == 0) {
3539                 lsb -= 1;
3540             } else {
3541                 // Search for lowest order nonzero int
3542                 int i,b;
3543                 for (i=0; (b = getInt(i)) == 0; i++)
3544                     ;
3545                 lsb += (i << 5) + Integer.numberOfTrailingZeros(b);
3546             }
3547             lowestSetBitPlusTwo = lsb + 2;
3548         }
3549         return lsb;
3550     }
3551 
3552 
3553     // Miscellaneous Bit Operations
3554 
3555     /**
3556      * Returns the number of bits in the minimal two's-complement
3557      * representation of this BigInteger, <em>excluding</em> a sign bit.
3558      * For positive BigIntegers, this is equivalent to the number of bits in
3559      * the ordinary binary representation.  (Computes
3560      * {@code (ceil(log2(this < 0 ? -this : this+1)))}.)
3561      *
3562      * @return number of bits in the minimal two's-complement
3563      *         representation of this BigInteger, <em>excluding</em> a sign bit.
3564      */
3565     public int bitLength() {
3566         int n = bitLengthPlusOne - 1;
3567         if (n == -1) { // bitLength not initialized yet
3568             int[] m = mag;
3569             int len = m.length;
3570             if (len == 0) {
3571                 n = 0; // offset by one to initialize
3572             }  else {
3573                 // Calculate the bit length of the magnitude
3574                 int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]);
3575                  if (signum < 0) {
3576                      // Check if magnitude is a power of two
3577                      boolean pow2 = (Integer.bitCount(mag[0]) == 1);
3578                      for (int i=1; i< len && pow2; i++)
3579                          pow2 = (mag[i] == 0);
3580 
3581                      n = (pow2 ? magBitLength -1 : magBitLength);
3582                  } else {
3583                      n = magBitLength;


4020         int byteLen = bitLength()/8 + 1;
4021         byte[] byteArray = new byte[byteLen];
4022 
4023         for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i >= 0; i--) {
4024             if (bytesCopied == 4) {
4025                 nextInt = getInt(intIndex++);
4026                 bytesCopied = 1;
4027             } else {
4028                 nextInt >>>= 8;
4029                 bytesCopied++;
4030             }
4031             byteArray[i] = (byte)nextInt;
4032         }
4033         return byteArray;
4034     }
4035 
4036     /**
4037      * Converts this BigInteger to an {@code int}.  This
4038      * conversion is analogous to a
4039      * <i>narrowing primitive conversion</i> from {@code long} to
4040      * {@code int} as defined in
4041      * <cite>The Java&trade; Language Specification</cite>:
4042      * if this BigInteger is too big to fit in an
4043      * {@code int}, only the low-order 32 bits are returned.
4044      * Note that this conversion can lose information about the
4045      * overall magnitude of the BigInteger value as well as return a
4046      * result with the opposite sign.
4047      *
4048      * @return this BigInteger converted to an {@code int}.
4049      * @see #intValueExact()
4050      * @jls 5.1.3 Narrowing Primitive Conversion
4051      */
4052     public int intValue() {
4053         int result = 0;
4054         result = getInt(0);
4055         return result;
4056     }
4057 
4058     /**
4059      * Converts this BigInteger to a {@code long}.  This
4060      * conversion is analogous to a
4061      * <i>narrowing primitive conversion</i> from {@code long} to
4062      * {@code int} as defined in
4063      * <cite>The Java&trade; Language Specification</cite>:
4064      * if this BigInteger is too big to fit in a
4065      * {@code long}, only the low-order 64 bits are returned.
4066      * Note that this conversion can lose information about the
4067      * overall magnitude of the BigInteger value as well as return a
4068      * result with the opposite sign.
4069      *
4070      * @return this BigInteger converted to a {@code long}.
4071      * @see #longValueExact()
4072      * @jls 5.1.3 Narrowing Primitive Conversion
4073      */
4074     public long longValue() {
4075         long result = 0;
4076 
4077         for (int i=1; i >= 0; i--)
4078             result = (result << 32) + (getInt(i) & LONG_MASK);
4079         return result;
4080     }
4081 
4082     /**
4083      * Converts this BigInteger to a {@code float}.  This
4084      * conversion is similar to the
4085      * <i>narrowing primitive conversion</i> from {@code double} to
4086      * {@code float} as defined in
4087      * <cite>The Java&trade; Language Specification</cite>:
4088      * if this BigInteger has too great a magnitude
4089      * to represent as a {@code float}, it will be converted to
4090      * {@link Float#NEGATIVE_INFINITY} or {@link
4091      * Float#POSITIVE_INFINITY} as appropriate.  Note that even when
4092      * the return value is finite, this conversion can lose
4093      * information about the precision of the BigInteger value.
4094      *
4095      * @return this BigInteger converted to a {@code float}.
4096      * @jls 5.1.3 Narrowing Primitive Conversion
4097      */
4098     public float floatValue() {
4099         if (signum == 0) {
4100             return 0.0f;
4101         }
4102 
4103         int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;
4104 
4105         // exponent == floor(log2(abs(this)))
4106         if (exponent < Long.SIZE - 1) {
4107             return longValue();
4108         } else if (exponent > Float.MAX_EXPONENT) {
4109             return signum > 0 ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;
4110         }
4111 
4112         /*
4113          * We need the top SIGNIFICAND_WIDTH bits, including the "implicit"
4114          * one bit. To make rounding easier, we pick out the top
4115          * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or
4116          * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1


4151                 && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);
4152         int signifRounded = increment ? signifFloor + 1 : signifFloor;
4153         int bits = ((exponent + FloatConsts.EXP_BIAS))
4154                 << (FloatConsts.SIGNIFICAND_WIDTH - 1);
4155         bits += signifRounded;
4156         /*
4157          * If signifRounded == 2^24, we'd need to set all of the significand
4158          * bits to zero and add 1 to the exponent. This is exactly the behavior
4159          * we get from just adding signifRounded to bits directly. If the
4160          * exponent is Float.MAX_EXPONENT, we round up (correctly) to
4161          * Float.POSITIVE_INFINITY.
4162          */
4163         bits |= signum & FloatConsts.SIGN_BIT_MASK;
4164         return Float.intBitsToFloat(bits);
4165     }
4166 
4167     /**
4168      * Converts this BigInteger to a {@code double}.  This
4169      * conversion is similar to the
4170      * <i>narrowing primitive conversion</i> from {@code double} to
4171      * {@code float} as defined in
4172      * <cite>The Java&trade; Language Specification</cite>:
4173      * if this BigInteger has too great a magnitude
4174      * to represent as a {@code double}, it will be converted to
4175      * {@link Double#NEGATIVE_INFINITY} or {@link
4176      * Double#POSITIVE_INFINITY} as appropriate.  Note that even when
4177      * the return value is finite, this conversion can lose
4178      * information about the precision of the BigInteger value.
4179      *
4180      * @return this BigInteger converted to a {@code double}.
4181      * @jls 5.1.3 Narrowing Primitive Conversion
4182      */
4183     public double doubleValue() {
4184         if (signum == 0) {
4185             return 0.0;
4186         }
4187 
4188         int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;
4189 
4190         // exponent == floor(log2(abs(this))Double)
4191         if (exponent < Long.SIZE - 1) {
4192             return longValue();
4193         } else if (exponent > Double.MAX_EXPONENT) {
4194             return signum > 0 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
4195         }
4196 
4197         /*
4198          * We need the top SIGNIFICAND_WIDTH bits, including the "implicit"
4199          * one bit. To make rounding easier, we pick out the top
4200          * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or
4201          * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1


< prev index next >