Path: blob/master/src/java.base/share/classes/jdk/internal/math/FloatingDecimal.java
41159 views
/*1* Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package jdk.internal.math;2627import java.util.Arrays;28import java.util.regex.*;2930/**31* A class for converting between ASCII and decimal representations of a single32* or double precision floating point number. Most conversions are provided via33* static convenience methods, although a <code>BinaryToASCIIConverter</code>34* instance may be obtained and reused.35*/36public class FloatingDecimal{37//38// Constants of the implementation;39// most are IEEE-754 related.40// (There are more really boring constants at the end.)41//42static final int EXP_SHIFT = DoubleConsts.SIGNIFICAND_WIDTH - 1;43static final long FRACT_HOB = ( 1L<<EXP_SHIFT ); // assumed High-Order bit44static final long EXP_ONE = ((long)DoubleConsts.EXP_BIAS)<<EXP_SHIFT; // exponent of 1.045static final int MAX_SMALL_BIN_EXP = 62;46static final int MIN_SMALL_BIN_EXP = -( 63 / 3 );47static final int MAX_DECIMAL_DIGITS = 15;48static final int MAX_DECIMAL_EXPONENT = 308;49static final int MIN_DECIMAL_EXPONENT = -324;50static final int BIG_DECIMAL_EXPONENT = 324; // i.e. abs(MIN_DECIMAL_EXPONENT)51static final int MAX_NDIGITS = 1100;5253static final int SINGLE_EXP_SHIFT = FloatConsts.SIGNIFICAND_WIDTH - 1;54static final int SINGLE_FRACT_HOB = 1<<SINGLE_EXP_SHIFT;55static final int SINGLE_MAX_DECIMAL_DIGITS = 7;56static final int SINGLE_MAX_DECIMAL_EXPONENT = 38;57static final int SINGLE_MIN_DECIMAL_EXPONENT = -45;58static final int SINGLE_MAX_NDIGITS = 200;5960static final int INT_DECIMAL_DIGITS = 9;6162/**63* Converts a double precision floating point value to a <code>String</code>.64*65* @param d The double precision value.66* @return The value converted to a <code>String</code>.67*/68public static String toJavaFormatString(double d) {69return getBinaryToASCIIConverter(d).toJavaFormatString();70}7172/**73* Converts a single precision floating point value to a <code>String</code>.74*75* @param f The single precision value.76* @return The value converted to a <code>String</code>.77*/78public static String toJavaFormatString(float f) {79return getBinaryToASCIIConverter(f).toJavaFormatString();80}8182/**83* Appends a double precision floating point value to an <code>Appendable</code>.84* @param d The double precision value.85* @param buf The <code>Appendable</code> with the value appended.86*/87public static void appendTo(double d, Appendable buf) {88getBinaryToASCIIConverter(d).appendTo(buf);89}9091/**92* Appends a single precision floating point value to an <code>Appendable</code>.93* @param f The single precision value.94* @param buf The <code>Appendable</code> with the value appended.95*/96public static void appendTo(float f, Appendable buf) {97getBinaryToASCIIConverter(f).appendTo(buf);98}99100/**101* Converts a <code>String</code> to a double precision floating point value.102*103* @param s The <code>String</code> to convert.104* @return The double precision value.105* @throws NumberFormatException If the <code>String</code> does not106* represent a properly formatted double precision value.107*/108public static double parseDouble(String s) throws NumberFormatException {109return readJavaFormatString(s).doubleValue();110}111112/**113* Converts a <code>String</code> to a single precision floating point value.114*115* @param s The <code>String</code> to convert.116* @return The single precision value.117* @throws NumberFormatException If the <code>String</code> does not118* represent a properly formatted single precision value.119*/120public static float parseFloat(String s) throws NumberFormatException {121return readJavaFormatString(s).floatValue();122}123124/**125* A converter which can process single or double precision floating point126* values into an ASCII <code>String</code> representation.127*/128public interface BinaryToASCIIConverter {129/**130* Converts a floating point value into an ASCII <code>String</code>.131* @return The value converted to a <code>String</code>.132*/133String toJavaFormatString();134135/**136* Appends a floating point value to an <code>Appendable</code>.137* @param buf The <code>Appendable</code> to receive the value.138*/139void appendTo(Appendable buf);140141/**142* Retrieves the decimal exponent most closely corresponding to this value.143* @return The decimal exponent.144*/145int getDecimalExponent();146147/**148* Retrieves the value as an array of digits.149* @param digits The digit array.150* @return The number of valid digits copied into the array.151*/152int getDigits(char[] digits);153154/**155* Indicates the sign of the value.156* @return {@code value < 0.0}.157*/158boolean isNegative();159160/**161* Indicates whether the value is either infinite or not a number.162*163* @return <code>true</code> if and only if the value is <code>NaN</code>164* or infinite.165*/166boolean isExceptional();167168/**169* Indicates whether the value was rounded up during the binary to ASCII170* conversion.171*172* @return <code>true</code> if and only if the value was rounded up.173*/174boolean digitsRoundedUp();175176/**177* Indicates whether the binary to ASCII conversion was exact.178*179* @return <code>true</code> if any only if the conversion was exact.180*/181boolean decimalDigitsExact();182}183184/**185* A <code>BinaryToASCIIConverter</code> which represents <code>NaN</code>186* and infinite values.187*/188private static class ExceptionalBinaryToASCIIBuffer implements BinaryToASCIIConverter {189private final String image;190private boolean isNegative;191192public ExceptionalBinaryToASCIIBuffer(String image, boolean isNegative) {193this.image = image;194this.isNegative = isNegative;195}196197@Override198public String toJavaFormatString() {199return image;200}201202@Override203public void appendTo(Appendable buf) {204if (buf instanceof StringBuilder) {205((StringBuilder) buf).append(image);206} else if (buf instanceof StringBuffer) {207((StringBuffer) buf).append(image);208} else {209assert false;210}211}212213@Override214public int getDecimalExponent() {215throw new IllegalArgumentException("Exceptional value does not have an exponent");216}217218@Override219public int getDigits(char[] digits) {220throw new IllegalArgumentException("Exceptional value does not have digits");221}222223@Override224public boolean isNegative() {225return isNegative;226}227228@Override229public boolean isExceptional() {230return true;231}232233@Override234public boolean digitsRoundedUp() {235throw new IllegalArgumentException("Exceptional value is not rounded");236}237238@Override239public boolean decimalDigitsExact() {240throw new IllegalArgumentException("Exceptional value is not exact");241}242}243244private static final String INFINITY_REP = "Infinity";245private static final int INFINITY_LENGTH = INFINITY_REP.length();246private static final String NAN_REP = "NaN";247private static final int NAN_LENGTH = NAN_REP.length();248249private static final BinaryToASCIIConverter B2AC_POSITIVE_INFINITY = new ExceptionalBinaryToASCIIBuffer(INFINITY_REP, false);250private static final BinaryToASCIIConverter B2AC_NEGATIVE_INFINITY = new ExceptionalBinaryToASCIIBuffer("-" + INFINITY_REP, true);251private static final BinaryToASCIIConverter B2AC_NOT_A_NUMBER = new ExceptionalBinaryToASCIIBuffer(NAN_REP, false);252private static final BinaryToASCIIConverter B2AC_POSITIVE_ZERO = new BinaryToASCIIBuffer(false, new char[]{'0'});253private static final BinaryToASCIIConverter B2AC_NEGATIVE_ZERO = new BinaryToASCIIBuffer(true, new char[]{'0'});254255/**256* A buffered implementation of <code>BinaryToASCIIConverter</code>.257*/258static class BinaryToASCIIBuffer implements BinaryToASCIIConverter {259private boolean isNegative;260private int decExponent;261private int firstDigitIndex;262private int nDigits;263private final char[] digits;264private final char[] buffer = new char[26];265266//267// The fields below provide additional information about the result of268// the binary to decimal digits conversion done in dtoa() and roundup()269// methods. They are changed if needed by those two methods.270//271272// True if the dtoa() binary to decimal conversion was exact.273private boolean exactDecimalConversion = false;274275// True if the result of the binary to decimal conversion was rounded-up276// at the end of the conversion process, i.e. roundUp() method was called.277private boolean decimalDigitsRoundedUp = false;278279/**280* Default constructor; used for non-zero values,281* <code>BinaryToASCIIBuffer</code> may be thread-local and reused282*/283BinaryToASCIIBuffer(){284this.digits = new char[20];285}286287/**288* Creates a specialized value (positive and negative zeros).289*/290BinaryToASCIIBuffer(boolean isNegative, char[] digits){291this.isNegative = isNegative;292this.decExponent = 0;293this.digits = digits;294this.firstDigitIndex = 0;295this.nDigits = digits.length;296}297298@Override299public String toJavaFormatString() {300int len = getChars(buffer);301return new String(buffer, 0, len);302}303304@Override305public void appendTo(Appendable buf) {306int len = getChars(buffer);307if (buf instanceof StringBuilder) {308((StringBuilder) buf).append(buffer, 0, len);309} else if (buf instanceof StringBuffer) {310((StringBuffer) buf).append(buffer, 0, len);311} else {312assert false;313}314}315316@Override317public int getDecimalExponent() {318return decExponent;319}320321@Override322public int getDigits(char[] digits) {323System.arraycopy(this.digits, firstDigitIndex, digits, 0, this.nDigits);324return this.nDigits;325}326327@Override328public boolean isNegative() {329return isNegative;330}331332@Override333public boolean isExceptional() {334return false;335}336337@Override338public boolean digitsRoundedUp() {339return decimalDigitsRoundedUp;340}341342@Override343public boolean decimalDigitsExact() {344return exactDecimalConversion;345}346347private void setSign(boolean isNegative) {348this.isNegative = isNegative;349}350351/**352* This is the easy subcase --353* all the significant bits, after scaling, are held in lvalue.354* negSign and decExponent tell us what processing and scaling355* has already been done. Exceptional cases have already been356* stripped out.357* In particular:358* lvalue is a finite number (not Inf, nor NaN)359* lvalue > 0L (not zero, nor negative).360*361* The only reason that we develop the digits here, rather than362* calling on Long.toString() is that we can do it a little faster,363* and besides want to treat trailing 0s specially. If Long.toString364* changes, we should re-evaluate this strategy!365*/366private void developLongDigits( int decExponent, long lvalue, int insignificantDigits ){367if ( insignificantDigits != 0 ){368// Discard non-significant low-order bits, while rounding,369// up to insignificant value.370long pow10 = FDBigInteger.LONG_5_POW[insignificantDigits] << insignificantDigits; // 10^i == 5^i * 2^i;371long residue = lvalue % pow10;372lvalue /= pow10;373decExponent += insignificantDigits;374if ( residue >= (pow10>>1) ){375// round up based on the low-order bits we're discarding376lvalue++;377}378}379int digitno = digits.length -1;380int c;381if ( lvalue <= Integer.MAX_VALUE ){382assert lvalue > 0L : lvalue; // lvalue <= 0383// even easier subcase!384// can do int arithmetic rather than long!385int ivalue = (int)lvalue;386c = ivalue%10;387ivalue /= 10;388while ( c == 0 ){389decExponent++;390c = ivalue%10;391ivalue /= 10;392}393while ( ivalue != 0){394digits[digitno--] = (char)(c+'0');395decExponent++;396c = ivalue%10;397ivalue /= 10;398}399digits[digitno] = (char)(c+'0');400} else {401// same algorithm as above (same bugs, too )402// but using long arithmetic.403c = (int)(lvalue%10L);404lvalue /= 10L;405while ( c == 0 ){406decExponent++;407c = (int)(lvalue%10L);408lvalue /= 10L;409}410while ( lvalue != 0L ){411digits[digitno--] = (char)(c+'0');412decExponent++;413c = (int)(lvalue%10L);414lvalue /= 10;415}416digits[digitno] = (char)(c+'0');417}418this.decExponent = decExponent+1;419this.firstDigitIndex = digitno;420this.nDigits = this.digits.length - digitno;421}422423private void dtoa( int binExp, long fractBits, int nSignificantBits, boolean isCompatibleFormat)424{425assert fractBits > 0 ; // fractBits here can't be zero or negative426assert (fractBits & FRACT_HOB)!=0 ; // Hi-order bit should be set427// Examine number. Determine if it is an easy case,428// which we can do pretty trivially using float/long conversion,429// or whether we must do real work.430final int tailZeros = Long.numberOfTrailingZeros(fractBits);431432// number of significant bits of fractBits;433final int nFractBits = EXP_SHIFT+1-tailZeros;434435// reset flags to default values as dtoa() does not always set these436// flags and a prior call to dtoa() might have set them to incorrect437// values with respect to the current state.438decimalDigitsRoundedUp = false;439exactDecimalConversion = false;440441// number of significant bits to the right of the point.442int nTinyBits = Math.max( 0, nFractBits - binExp - 1 );443if ( binExp <= MAX_SMALL_BIN_EXP && binExp >= MIN_SMALL_BIN_EXP ){444// Look more closely at the number to decide if,445// with scaling by 10^nTinyBits, the result will fit in446// a long.447if ( (nTinyBits < FDBigInteger.LONG_5_POW.length) && ((nFractBits + N_5_BITS[nTinyBits]) < 64 ) ){448//449// We can do this:450// take the fraction bits, which are normalized.451// (a) nTinyBits == 0: Shift left or right appropriately452// to align the binary point at the extreme right, i.e.453// where a long int point is expected to be. The integer454// result is easily converted to a string.455// (b) nTinyBits > 0: Shift right by EXP_SHIFT-nFractBits,456// which effectively converts to long and scales by457// 2^nTinyBits. Then multiply by 5^nTinyBits to458// complete the scaling. We know this won't overflow459// because we just counted the number of bits necessary460// in the result. The integer you get from this can461// then be converted to a string pretty easily.462//463if ( nTinyBits == 0 ) {464int insignificant;465if ( binExp > nSignificantBits ){466insignificant = insignificantDigitsForPow2(binExp-nSignificantBits-1);467} else {468insignificant = 0;469}470if ( binExp >= EXP_SHIFT ){471fractBits <<= (binExp-EXP_SHIFT);472} else {473fractBits >>>= (EXP_SHIFT-binExp) ;474}475developLongDigits( 0, fractBits, insignificant );476return;477}478//479// The following causes excess digits to be printed480// out in the single-float case. Our manipulation of481// halfULP here is apparently not correct. If we482// better understand how this works, perhaps we can483// use this special case again. But for the time being,484// we do not.485// else {486// fractBits >>>= EXP_SHIFT+1-nFractBits;487// fractBits//= long5pow[ nTinyBits ];488// halfULP = long5pow[ nTinyBits ] >> (1+nSignificantBits-nFractBits);489// developLongDigits( -nTinyBits, fractBits, insignificantDigits(halfULP) );490// return;491// }492//493}494}495//496// This is the hard case. We are going to compute large positive497// integers B and S and integer decExp, s.t.498// d = ( B / S )// 10^decExp499// 1 <= B / S < 10500// Obvious choices are:501// decExp = floor( log10(d) )502// B = d// 2^nTinyBits// 10^max( 0, -decExp )503// S = 10^max( 0, decExp)// 2^nTinyBits504// (noting that nTinyBits has already been forced to non-negative)505// I am also going to compute a large positive integer506// M = (1/2^nSignificantBits)// 2^nTinyBits// 10^max( 0, -decExp )507// i.e. M is (1/2) of the ULP of d, scaled like B.508// When we iterate through dividing B/S and picking off the509// quotient bits, we will know when to stop when the remainder510// is <= M.511//512// We keep track of powers of 2 and powers of 5.513//514int decExp = estimateDecExp(fractBits,binExp);515int B2, B5; // powers of 2 and powers of 5, respectively, in B516int S2, S5; // powers of 2 and powers of 5, respectively, in S517int M2, M5; // powers of 2 and powers of 5, respectively, in M518519B5 = Math.max( 0, -decExp );520B2 = B5 + nTinyBits + binExp;521522S5 = Math.max( 0, decExp );523S2 = S5 + nTinyBits;524525M5 = B5;526M2 = B2 - nSignificantBits;527528//529// the long integer fractBits contains the (nFractBits) interesting530// bits from the mantissa of d ( hidden 1 added if necessary) followed531// by (EXP_SHIFT+1-nFractBits) zeros. In the interest of compactness,532// I will shift out those zeros before turning fractBits into a533// FDBigInteger. The resulting whole number will be534// d * 2^(nFractBits-1-binExp).535//536fractBits >>>= tailZeros;537B2 -= nFractBits-1;538int common2factor = Math.min( B2, S2 );539B2 -= common2factor;540S2 -= common2factor;541M2 -= common2factor;542543//544// HACK!! For exact powers of two, the next smallest number545// is only half as far away as we think (because the meaning of546// ULP changes at power-of-two bounds) for this reason, we547// hack M2. Hope this works.548//549if ( nFractBits == 1 ) {550M2 -= 1;551}552553if ( M2 < 0 ){554// oops.555// since we cannot scale M down far enough,556// we must scale the other values up.557B2 -= M2;558S2 -= M2;559M2 = 0;560}561//562// Construct, Scale, iterate.563// Some day, we'll write a stopping test that takes564// account of the asymmetry of the spacing of floating-point565// numbers below perfect powers of 2566// 26 Sept 96 is not that day.567// So we use a symmetric test.568//569int ndigit = 0;570boolean low, high;571long lowDigitDifference;572int q;573574//575// Detect the special cases where all the numbers we are about576// to compute will fit in int or long integers.577// In these cases, we will avoid doing FDBigInteger arithmetic.578// We use the same algorithms, except that we "normalize"579// our FDBigIntegers before iterating. This is to make division easier,580// as it makes our fist guess (quotient of high-order words)581// more accurate!582//583// Some day, we'll write a stopping test that takes584// account of the asymmetry of the spacing of floating-point585// numbers below perfect powers of 2586// 26 Sept 96 is not that day.587// So we use a symmetric test.588//589// binary digits needed to represent B, approx.590int Bbits = nFractBits + B2 + (( B5 < N_5_BITS.length )? N_5_BITS[B5] : ( B5*3 ));591592// binary digits needed to represent 10*S, approx.593int tenSbits = S2+1 + (( (S5+1) < N_5_BITS.length )? N_5_BITS[(S5+1)] : ( (S5+1)*3 ));594if ( Bbits < 64 && tenSbits < 64){595if ( Bbits < 32 && tenSbits < 32){596// wa-hoo! They're all ints!597int b = ((int)fractBits * FDBigInteger.SMALL_5_POW[B5] ) << B2;598int s = FDBigInteger.SMALL_5_POW[S5] << S2;599int m = FDBigInteger.SMALL_5_POW[M5] << M2;600int tens = s * 10;601//602// Unroll the first iteration. If our decExp estimate603// was too high, our first quotient will be zero. In this604// case, we discard it and decrement decExp.605//606ndigit = 0;607q = b / s;608b = 10 * ( b % s );609m *= 10;610low = (b < m );611high = (b+m > tens );612assert q < 10 : q; // excessively large digit613if ( (q == 0) && ! high ){614// oops. Usually ignore leading zero.615decExp--;616} else {617digits[ndigit++] = (char)('0' + q);618}619//620// HACK! Java spec sez that we always have at least621// one digit after the . in either F- or E-form output.622// Thus we will need more than one digit if we're using623// E-form624//625if ( !isCompatibleFormat ||decExp < -3 || decExp >= 8 ){626high = low = false;627}628while( ! low && ! high ){629q = b / s;630b = 10 * ( b % s );631m *= 10;632assert q < 10 : q; // excessively large digit633if ( m > 0L ){634low = (b < m );635high = (b+m > tens );636} else {637// hack -- m might overflow!638// in this case, it is certainly > b,639// which won't640// and b+m > tens, too, since that has overflowed641// either!642low = true;643high = true;644}645digits[ndigit++] = (char)('0' + q);646}647lowDigitDifference = (b<<1) - tens;648exactDecimalConversion = (b == 0);649} else {650// still good! they're all longs!651long b = (fractBits * FDBigInteger.LONG_5_POW[B5] ) << B2;652long s = FDBigInteger.LONG_5_POW[S5] << S2;653long m = FDBigInteger.LONG_5_POW[M5] << M2;654long tens = s * 10L;655//656// Unroll the first iteration. If our decExp estimate657// was too high, our first quotient will be zero. In this658// case, we discard it and decrement decExp.659//660ndigit = 0;661q = (int) ( b / s );662b = 10L * ( b % s );663m *= 10L;664low = (b < m );665high = (b+m > tens );666assert q < 10 : q; // excessively large digit667if ( (q == 0) && ! high ){668// oops. Usually ignore leading zero.669decExp--;670} else {671digits[ndigit++] = (char)('0' + q);672}673//674// HACK! Java spec sez that we always have at least675// one digit after the . in either F- or E-form output.676// Thus we will need more than one digit if we're using677// E-form678//679if ( !isCompatibleFormat || decExp < -3 || decExp >= 8 ){680high = low = false;681}682while( ! low && ! high ){683q = (int) ( b / s );684b = 10 * ( b % s );685m *= 10;686assert q < 10 : q; // excessively large digit687if ( m > 0L ){688low = (b < m );689high = (b+m > tens );690} else {691// hack -- m might overflow!692// in this case, it is certainly > b,693// which won't694// and b+m > tens, too, since that has overflowed695// either!696low = true;697high = true;698}699digits[ndigit++] = (char)('0' + q);700}701lowDigitDifference = (b<<1) - tens;702exactDecimalConversion = (b == 0);703}704} else {705//706// We really must do FDBigInteger arithmetic.707// Fist, construct our FDBigInteger initial values.708//709FDBigInteger Sval = FDBigInteger.valueOfPow52(S5, S2);710int shiftBias = Sval.getNormalizationBias();711Sval = Sval.leftShift(shiftBias); // normalize so that division works better712713FDBigInteger Bval = FDBigInteger.valueOfMulPow52(fractBits, B5, B2 + shiftBias);714FDBigInteger Mval = FDBigInteger.valueOfPow52(M5 + 1, M2 + shiftBias + 1);715716FDBigInteger tenSval = FDBigInteger.valueOfPow52(S5 + 1, S2 + shiftBias + 1); //Sval.mult( 10 );717//718// Unroll the first iteration. If our decExp estimate719// was too high, our first quotient will be zero. In this720// case, we discard it and decrement decExp.721//722ndigit = 0;723q = Bval.quoRemIteration( Sval );724low = (Bval.cmp( Mval ) < 0);725high = tenSval.addAndCmp(Bval,Mval)<=0;726727assert q < 10 : q; // excessively large digit728if ( (q == 0) && ! high ){729// oops. Usually ignore leading zero.730decExp--;731} else {732digits[ndigit++] = (char)('0' + q);733}734//735// HACK! Java spec sez that we always have at least736// one digit after the . in either F- or E-form output.737// Thus we will need more than one digit if we're using738// E-form739//740if (!isCompatibleFormat || decExp < -3 || decExp >= 8 ){741high = low = false;742}743while( ! low && ! high ){744q = Bval.quoRemIteration( Sval );745assert q < 10 : q; // excessively large digit746Mval = Mval.multBy10(); //Mval = Mval.mult( 10 );747low = (Bval.cmp( Mval ) < 0);748high = tenSval.addAndCmp(Bval,Mval)<=0;749digits[ndigit++] = (char)('0' + q);750}751if ( high && low ){752Bval = Bval.leftShift(1);753lowDigitDifference = Bval.cmp(tenSval);754} else {755lowDigitDifference = 0L; // this here only for flow analysis!756}757exactDecimalConversion = (Bval.cmp( FDBigInteger.ZERO ) == 0);758}759this.decExponent = decExp+1;760this.firstDigitIndex = 0;761this.nDigits = ndigit;762//763// Last digit gets rounded based on stopping condition.764//765if ( high ){766if ( low ){767if ( lowDigitDifference == 0L ){768// it's a tie!769// choose based on which digits we like.770if ( (digits[firstDigitIndex+nDigits-1]&1) != 0 ) {771roundup();772}773} else if ( lowDigitDifference > 0 ){774roundup();775}776} else {777roundup();778}779}780}781782// add one to the least significant digit.783// in the unlikely event there is a carry out, deal with it.784// assert that this will only happen where there785// is only one digit, e.g. (float)1e-44 seems to do it.786//787private void roundup() {788int i = (firstDigitIndex + nDigits - 1);789int q = digits[i];790if (q == '9') {791while (q == '9' && i > firstDigitIndex) {792digits[i] = '0';793q = digits[--i];794}795if (q == '9') {796// carryout! High-order 1, rest 0s, larger exp.797decExponent += 1;798digits[firstDigitIndex] = '1';799return;800}801// else fall through.802}803digits[i] = (char) (q + 1);804decimalDigitsRoundedUp = true;805}806807/**808* Estimate decimal exponent. (If it is small-ish,809* we could double-check.)810*811* First, scale the mantissa bits such that 1 <= d2 < 2.812* We are then going to estimate813* log10(d2) ~=~ (d2-1.5)/1.5 + log(1.5)814* and so we can estimate815* log10(d) ~=~ log10(d2) + binExp * log10(2)816* take the floor and call it decExp.817*/818static int estimateDecExp(long fractBits, int binExp) {819double d2 = Double.longBitsToDouble( EXP_ONE | ( fractBits & DoubleConsts.SIGNIF_BIT_MASK ) );820double d = (d2-1.5D)*0.289529654D + 0.176091259 + (double)binExp * 0.301029995663981;821long dBits = Double.doubleToRawLongBits(d); //can't be NaN here so use raw822int exponent = (int)((dBits & DoubleConsts.EXP_BIT_MASK) >> EXP_SHIFT) - DoubleConsts.EXP_BIAS;823boolean isNegative = (dBits & DoubleConsts.SIGN_BIT_MASK) != 0; // discover sign824if(exponent>=0 && exponent<52) { // hot path825long mask = DoubleConsts.SIGNIF_BIT_MASK >> exponent;826int r = (int)(( (dBits&DoubleConsts.SIGNIF_BIT_MASK) | FRACT_HOB )>>(EXP_SHIFT-exponent));827return isNegative ? (((mask & dBits) == 0L ) ? -r : -r-1 ) : r;828} else if (exponent < 0) {829return (((dBits&~DoubleConsts.SIGN_BIT_MASK) == 0) ? 0 :830( (isNegative) ? -1 : 0) );831} else { //if (exponent >= 52)832return (int)d;833}834}835836private static int insignificantDigits(int insignificant) {837int i;838for ( i = 0; insignificant >= 10L; i++ ) {839insignificant /= 10L;840}841return i;842}843844/**845* Calculates846* <pre>847* insignificantDigitsForPow2(v) == insignificantDigits(1L<<v)848* </pre>849*/850private static int insignificantDigitsForPow2(int p2) {851if (p2 > 1 && p2 < insignificantDigitsNumber.length) {852return insignificantDigitsNumber[p2];853}854return 0;855}856857/**858* If insignificant==(1L << ixd)859* i = insignificantDigitsNumber[idx] is the same as:860* int i;861* for ( i = 0; insignificant >= 10L; i++ )862* insignificant /= 10L;863*/864private static final int[] insignificantDigitsNumber = {8650, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3,8664, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7,8678, 8, 8, 9, 9, 9, 9, 10, 10, 10, 11, 11, 11,86812, 12, 12, 12, 13, 13, 13, 14, 14, 14,86915, 15, 15, 15, 16, 16, 16, 17, 17, 17,87018, 18, 18, 19871};872873// approximately ceil( log2( long5pow[i] ) )874private static final int[] N_5_BITS = {8750,8763,8775,8787,87910,88012,88114,88217,88319,88421,88524,88626,88728,88831,88933,89035,89138,89240,89342,89445,89547,89649,89752,89854,89956,90059,90161,902};903904private int getChars(char[] result) {905assert nDigits <= 19 : nDigits; // generous bound on size of nDigits906int i = 0;907if (isNegative) {908result[0] = '-';909i = 1;910}911if (decExponent > 0 && decExponent < 8) {912// print digits.digits.913int charLength = Math.min(nDigits, decExponent);914System.arraycopy(digits, firstDigitIndex, result, i, charLength);915i += charLength;916if (charLength < decExponent) {917charLength = decExponent - charLength;918Arrays.fill(result,i,i+charLength,'0');919i += charLength;920result[i++] = '.';921result[i++] = '0';922} else {923result[i++] = '.';924if (charLength < nDigits) {925int t = nDigits - charLength;926System.arraycopy(digits, firstDigitIndex+charLength, result, i, t);927i += t;928} else {929result[i++] = '0';930}931}932} else if (decExponent <= 0 && decExponent > -3) {933result[i++] = '0';934result[i++] = '.';935if (decExponent != 0) {936Arrays.fill(result, i, i-decExponent, '0');937i -= decExponent;938}939System.arraycopy(digits, firstDigitIndex, result, i, nDigits);940i += nDigits;941} else {942result[i++] = digits[firstDigitIndex];943result[i++] = '.';944if (nDigits > 1) {945System.arraycopy(digits, firstDigitIndex+1, result, i, nDigits - 1);946i += nDigits - 1;947} else {948result[i++] = '0';949}950result[i++] = 'E';951int e;952if (decExponent <= 0) {953result[i++] = '-';954e = -decExponent + 1;955} else {956e = decExponent - 1;957}958// decExponent has 1, 2, or 3, digits959if (e <= 9) {960result[i++] = (char) (e + '0');961} else if (e <= 99) {962result[i++] = (char) (e / 10 + '0');963result[i++] = (char) (e % 10 + '0');964} else {965result[i++] = (char) (e / 100 + '0');966e %= 100;967result[i++] = (char) (e / 10 + '0');968result[i++] = (char) (e % 10 + '0');969}970}971return i;972}973974}975976private static final ThreadLocal<BinaryToASCIIBuffer> threadLocalBinaryToASCIIBuffer =977new ThreadLocal<BinaryToASCIIBuffer>() {978@Override979protected BinaryToASCIIBuffer initialValue() {980return new BinaryToASCIIBuffer();981}982};983984private static BinaryToASCIIBuffer getBinaryToASCIIBuffer() {985return threadLocalBinaryToASCIIBuffer.get();986}987988/**989* A converter which can process an ASCII <code>String</code> representation990* of a single or double precision floating point value into a991* <code>float</code> or a <code>double</code>.992*/993interface ASCIIToBinaryConverter {994995double doubleValue();996997float floatValue();998999}10001001/**1002* A <code>ASCIIToBinaryConverter</code> container for a <code>double</code>.1003*/1004static class PreparedASCIIToBinaryBuffer implements ASCIIToBinaryConverter {1005private final double doubleVal;1006private final float floatVal;10071008public PreparedASCIIToBinaryBuffer(double doubleVal, float floatVal) {1009this.doubleVal = doubleVal;1010this.floatVal = floatVal;1011}10121013@Override1014public double doubleValue() {1015return doubleVal;1016}10171018@Override1019public float floatValue() {1020return floatVal;1021}1022}10231024static final ASCIIToBinaryConverter A2BC_POSITIVE_INFINITY = new PreparedASCIIToBinaryBuffer(Double.POSITIVE_INFINITY, Float.POSITIVE_INFINITY);1025static final ASCIIToBinaryConverter A2BC_NEGATIVE_INFINITY = new PreparedASCIIToBinaryBuffer(Double.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY);1026static final ASCIIToBinaryConverter A2BC_NOT_A_NUMBER = new PreparedASCIIToBinaryBuffer(Double.NaN, Float.NaN);1027static final ASCIIToBinaryConverter A2BC_POSITIVE_ZERO = new PreparedASCIIToBinaryBuffer(0.0d, 0.0f);1028static final ASCIIToBinaryConverter A2BC_NEGATIVE_ZERO = new PreparedASCIIToBinaryBuffer(-0.0d, -0.0f);10291030/**1031* A buffered implementation of <code>ASCIIToBinaryConverter</code>.1032*/1033static class ASCIIToBinaryBuffer implements ASCIIToBinaryConverter {1034boolean isNegative;1035int decExponent;1036char digits[];1037int nDigits;10381039ASCIIToBinaryBuffer( boolean negSign, int decExponent, char[] digits, int n)1040{1041this.isNegative = negSign;1042this.decExponent = decExponent;1043this.digits = digits;1044this.nDigits = n;1045}10461047/**1048* Takes a FloatingDecimal, which we presumably just scanned in,1049* and finds out what its value is, as a double.1050*1051* AS A SIDE EFFECT, SET roundDir TO INDICATE PREFERRED1052* ROUNDING DIRECTION in case the result is really destined1053* for a single-precision float.1054*/1055@Override1056public double doubleValue() {1057int kDigits = Math.min(nDigits, MAX_DECIMAL_DIGITS + 1);1058//1059// convert the lead kDigits to a long integer.1060//1061// (special performance hack: start to do it using int)1062int iValue = (int) digits[0] - (int) '0';1063int iDigits = Math.min(kDigits, INT_DECIMAL_DIGITS);1064for (int i = 1; i < iDigits; i++) {1065iValue = iValue * 10 + (int) digits[i] - (int) '0';1066}1067long lValue = (long) iValue;1068for (int i = iDigits; i < kDigits; i++) {1069lValue = lValue * 10L + (long) ((int) digits[i] - (int) '0');1070}1071double dValue = (double) lValue;1072int exp = decExponent - kDigits;1073//1074// lValue now contains a long integer with the value of1075// the first kDigits digits of the number.1076// dValue contains the (double) of the same.1077//10781079if (nDigits <= MAX_DECIMAL_DIGITS) {1080//1081// possibly an easy case.1082// We know that the digits can be represented1083// exactly. And if the exponent isn't too outrageous,1084// the whole thing can be done with one operation,1085// thus one rounding error.1086// Note that all our constructors trim all leading and1087// trailing zeros, so simple values (including zero)1088// will always end up here1089//1090if (exp == 0 || dValue == 0.0) {1091return (isNegative) ? -dValue : dValue; // small floating integer1092}1093else if (exp >= 0) {1094if (exp <= MAX_SMALL_TEN) {1095//1096// Can get the answer with one operation,1097// thus one roundoff.1098//1099double rValue = dValue * SMALL_10_POW[exp];1100return (isNegative) ? -rValue : rValue;1101}1102int slop = MAX_DECIMAL_DIGITS - kDigits;1103if (exp <= MAX_SMALL_TEN + slop) {1104//1105// We can multiply dValue by 10^(slop)1106// and it is still "small" and exact.1107// Then we can multiply by 10^(exp-slop)1108// with one rounding.1109//1110dValue *= SMALL_10_POW[slop];1111double rValue = dValue * SMALL_10_POW[exp - slop];1112return (isNegative) ? -rValue : rValue;1113}1114//1115// Else we have a hard case with a positive exp.1116//1117} else {1118if (exp >= -MAX_SMALL_TEN) {1119//1120// Can get the answer in one division.1121//1122double rValue = dValue / SMALL_10_POW[-exp];1123return (isNegative) ? -rValue : rValue;1124}1125//1126// Else we have a hard case with a negative exp.1127//1128}1129}11301131//1132// Harder cases:1133// The sum of digits plus exponent is greater than1134// what we think we can do with one error.1135//1136// Start by approximating the right answer by,1137// naively, scaling by powers of 10.1138//1139if (exp > 0) {1140if (decExponent > MAX_DECIMAL_EXPONENT + 1) {1141//1142// Lets face it. This is going to be1143// Infinity. Cut to the chase.1144//1145return (isNegative) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;1146}1147if ((exp & 15) != 0) {1148dValue *= SMALL_10_POW[exp & 15];1149}1150if ((exp >>= 4) != 0) {1151int j;1152for (j = 0; exp > 1; j++, exp >>= 1) {1153if ((exp & 1) != 0) {1154dValue *= BIG_10_POW[j];1155}1156}1157//1158// The reason for the weird exp > 1 condition1159// in the above loop was so that the last multiply1160// would get unrolled. We handle it here.1161// It could overflow.1162//1163double t = dValue * BIG_10_POW[j];1164if (Double.isInfinite(t)) {1165//1166// It did overflow.1167// Look more closely at the result.1168// If the exponent is just one too large,1169// then use the maximum finite as our estimate1170// value. Else call the result infinity1171// and punt it.1172// ( I presume this could happen because1173// rounding forces the result here to be1174// an ULP or two larger than1175// Double.MAX_VALUE ).1176//1177t = dValue / 2.0;1178t *= BIG_10_POW[j];1179if (Double.isInfinite(t)) {1180return (isNegative) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;1181}1182t = Double.MAX_VALUE;1183}1184dValue = t;1185}1186} else if (exp < 0) {1187exp = -exp;1188if (decExponent < MIN_DECIMAL_EXPONENT - 1) {1189//1190// Lets face it. This is going to be1191// zero. Cut to the chase.1192//1193return (isNegative) ? -0.0 : 0.0;1194}1195if ((exp & 15) != 0) {1196dValue /= SMALL_10_POW[exp & 15];1197}1198if ((exp >>= 4) != 0) {1199int j;1200for (j = 0; exp > 1; j++, exp >>= 1) {1201if ((exp & 1) != 0) {1202dValue *= TINY_10_POW[j];1203}1204}1205//1206// The reason for the weird exp > 1 condition1207// in the above loop was so that the last multiply1208// would get unrolled. We handle it here.1209// It could underflow.1210//1211double t = dValue * TINY_10_POW[j];1212if (t == 0.0) {1213//1214// It did underflow.1215// Look more closely at the result.1216// If the exponent is just one too small,1217// then use the minimum finite as our estimate1218// value. Else call the result 0.01219// and punt it.1220// ( I presume this could happen because1221// rounding forces the result here to be1222// an ULP or two less than1223// Double.MIN_VALUE ).1224//1225t = dValue * 2.0;1226t *= TINY_10_POW[j];1227if (t == 0.0) {1228return (isNegative) ? -0.0 : 0.0;1229}1230t = Double.MIN_VALUE;1231}1232dValue = t;1233}1234}12351236//1237// dValue is now approximately the result.1238// The hard part is adjusting it, by comparison1239// with FDBigInteger arithmetic.1240// Formulate the EXACT big-number result as1241// bigD0 * 10^exp1242//1243if (nDigits > MAX_NDIGITS) {1244nDigits = MAX_NDIGITS + 1;1245digits[MAX_NDIGITS] = '1';1246}1247FDBigInteger bigD0 = new FDBigInteger(lValue, digits, kDigits, nDigits);1248exp = decExponent - nDigits;12491250long ieeeBits = Double.doubleToRawLongBits(dValue); // IEEE-754 bits of double candidate1251final int B5 = Math.max(0, -exp); // powers of 5 in bigB, value is not modified inside correctionLoop1252final int D5 = Math.max(0, exp); // powers of 5 in bigD, value is not modified inside correctionLoop1253bigD0 = bigD0.multByPow52(D5, 0);1254bigD0.makeImmutable(); // prevent bigD0 modification inside correctionLoop1255FDBigInteger bigD = null;1256int prevD2 = 0;12571258correctionLoop:1259while (true) {1260// here ieeeBits can't be NaN, Infinity or zero1261int binexp = (int) (ieeeBits >>> EXP_SHIFT);1262long bigBbits = ieeeBits & DoubleConsts.SIGNIF_BIT_MASK;1263if (binexp > 0) {1264bigBbits |= FRACT_HOB;1265} else { // Normalize denormalized numbers.1266assert bigBbits != 0L : bigBbits; // doubleToBigInt(0.0)1267int leadingZeros = Long.numberOfLeadingZeros(bigBbits);1268int shift = leadingZeros - (63 - EXP_SHIFT);1269bigBbits <<= shift;1270binexp = 1 - shift;1271}1272binexp -= DoubleConsts.EXP_BIAS;1273int lowOrderZeros = Long.numberOfTrailingZeros(bigBbits);1274bigBbits >>>= lowOrderZeros;1275final int bigIntExp = binexp - EXP_SHIFT + lowOrderZeros;1276final int bigIntNBits = EXP_SHIFT + 1 - lowOrderZeros;12771278//1279// Scale bigD, bigB appropriately for1280// big-integer operations.1281// Naively, we multiply by powers of ten1282// and powers of two. What we actually do1283// is keep track of the powers of 5 and1284// powers of 2 we would use, then factor out1285// common divisors before doing the work.1286//1287int B2 = B5; // powers of 2 in bigB1288int D2 = D5; // powers of 2 in bigD1289int Ulp2; // powers of 2 in halfUlp.1290if (bigIntExp >= 0) {1291B2 += bigIntExp;1292} else {1293D2 -= bigIntExp;1294}1295Ulp2 = B2;1296// shift bigB and bigD left by a number s. t.1297// halfUlp is still an integer.1298int hulpbias;1299if (binexp <= -DoubleConsts.EXP_BIAS) {1300// This is going to be a denormalized number1301// (if not actually zero).1302// half an ULP is at 2^-(DoubleConsts.EXP_BIAS+EXP_SHIFT+1)1303hulpbias = binexp + lowOrderZeros + DoubleConsts.EXP_BIAS;1304} else {1305hulpbias = 1 + lowOrderZeros;1306}1307B2 += hulpbias;1308D2 += hulpbias;1309// if there are common factors of 2, we might just as well1310// factor them out, as they add nothing useful.1311int common2 = Math.min(B2, Math.min(D2, Ulp2));1312B2 -= common2;1313D2 -= common2;1314Ulp2 -= common2;1315// do multiplications by powers of 5 and 21316FDBigInteger bigB = FDBigInteger.valueOfMulPow52(bigBbits, B5, B2);1317if (bigD == null || prevD2 != D2) {1318bigD = bigD0.leftShift(D2);1319prevD2 = D2;1320}1321//1322// to recap:1323// bigB is the scaled-big-int version of our floating-point1324// candidate.1325// bigD is the scaled-big-int version of the exact value1326// as we understand it.1327// halfUlp is 1/2 an ulp of bigB, except for special cases1328// of exact powers of 21329//1330// the plan is to compare bigB with bigD, and if the difference1331// is less than halfUlp, then we're satisfied. Otherwise,1332// use the ratio of difference to halfUlp to calculate a fudge1333// factor to add to the floating value, then go 'round again.1334//1335FDBigInteger diff;1336int cmpResult;1337boolean overvalue;1338if ((cmpResult = bigB.cmp(bigD)) > 0) {1339overvalue = true; // our candidate is too big.1340diff = bigB.leftInplaceSub(bigD); // bigB is not user further - reuse1341if ((bigIntNBits == 1) && (bigIntExp > -DoubleConsts.EXP_BIAS + 1)) {1342// candidate is a normalized exact power of 2 and1343// is too big (larger than Double.MIN_NORMAL). We will be subtracting.1344// For our purposes, ulp is the ulp of the1345// next smaller range.1346Ulp2 -= 1;1347if (Ulp2 < 0) {1348// rats. Cannot de-scale ulp this far.1349// must scale diff in other direction.1350Ulp2 = 0;1351diff = diff.leftShift(1);1352}1353}1354} else if (cmpResult < 0) {1355overvalue = false; // our candidate is too small.1356diff = bigD.rightInplaceSub(bigB); // bigB is not user further - reuse1357} else {1358// the candidate is exactly right!1359// this happens with surprising frequency1360break correctionLoop;1361}1362cmpResult = diff.cmpPow52(B5, Ulp2);1363if ((cmpResult) < 0) {1364// difference is small.1365// this is close enough1366break correctionLoop;1367} else if (cmpResult == 0) {1368// difference is exactly half an ULP1369// round to some other value maybe, then finish1370if ((ieeeBits & 1) != 0) { // half ties to even1371ieeeBits += overvalue ? -1 : 1; // nextDown or nextUp1372}1373break correctionLoop;1374} else {1375// difference is non-trivial.1376// could scale addend by ratio of difference to1377// halfUlp here, if we bothered to compute that difference.1378// Most of the time ( I hope ) it is about 1 anyway.1379ieeeBits += overvalue ? -1 : 1; // nextDown or nextUp1380if (ieeeBits == 0 || ieeeBits == DoubleConsts.EXP_BIT_MASK) { // 0.0 or Double.POSITIVE_INFINITY1381break correctionLoop; // oops. Fell off end of range.1382}1383continue; // try again.1384}13851386}1387if (isNegative) {1388ieeeBits |= DoubleConsts.SIGN_BIT_MASK;1389}1390return Double.longBitsToDouble(ieeeBits);1391}13921393/**1394* Takes a FloatingDecimal, which we presumably just scanned in,1395* and finds out what its value is, as a float.1396* This is distinct from doubleValue() to avoid the extremely1397* unlikely case of a double rounding error, wherein the conversion1398* to double has one rounding error, and the conversion of that double1399* to a float has another rounding error, IN THE WRONG DIRECTION,1400* ( because of the preference to a zero low-order bit ).1401*/1402@Override1403public float floatValue() {1404int kDigits = Math.min(nDigits, SINGLE_MAX_DECIMAL_DIGITS + 1);1405//1406// convert the lead kDigits to an integer.1407//1408int iValue = (int) digits[0] - (int) '0';1409for (int i = 1; i < kDigits; i++) {1410iValue = iValue * 10 + (int) digits[i] - (int) '0';1411}1412float fValue = (float) iValue;1413int exp = decExponent - kDigits;1414//1415// iValue now contains an integer with the value of1416// the first kDigits digits of the number.1417// fValue contains the (float) of the same.1418//14191420if (nDigits <= SINGLE_MAX_DECIMAL_DIGITS) {1421//1422// possibly an easy case.1423// We know that the digits can be represented1424// exactly. And if the exponent isn't too outrageous,1425// the whole thing can be done with one operation,1426// thus one rounding error.1427// Note that all our constructors trim all leading and1428// trailing zeros, so simple values (including zero)1429// will always end up here.1430//1431if (exp == 0 || fValue == 0.0f) {1432return (isNegative) ? -fValue : fValue; // small floating integer1433} else if (exp >= 0) {1434if (exp <= SINGLE_MAX_SMALL_TEN) {1435//1436// Can get the answer with one operation,1437// thus one roundoff.1438//1439fValue *= SINGLE_SMALL_10_POW[exp];1440return (isNegative) ? -fValue : fValue;1441}1442int slop = SINGLE_MAX_DECIMAL_DIGITS - kDigits;1443if (exp <= SINGLE_MAX_SMALL_TEN + slop) {1444//1445// We can multiply fValue by 10^(slop)1446// and it is still "small" and exact.1447// Then we can multiply by 10^(exp-slop)1448// with one rounding.1449//1450fValue *= SINGLE_SMALL_10_POW[slop];1451fValue *= SINGLE_SMALL_10_POW[exp - slop];1452return (isNegative) ? -fValue : fValue;1453}1454//1455// Else we have a hard case with a positive exp.1456//1457} else {1458if (exp >= -SINGLE_MAX_SMALL_TEN) {1459//1460// Can get the answer in one division.1461//1462fValue /= SINGLE_SMALL_10_POW[-exp];1463return (isNegative) ? -fValue : fValue;1464}1465//1466// Else we have a hard case with a negative exp.1467//1468}1469} else if ((decExponent >= nDigits) && (nDigits + decExponent <= MAX_DECIMAL_DIGITS)) {1470//1471// In double-precision, this is an exact floating integer.1472// So we can compute to double, then shorten to float1473// with one round, and get the right answer.1474//1475// First, finish accumulating digits.1476// Then convert that integer to a double, multiply1477// by the appropriate power of ten, and convert to float.1478//1479long lValue = (long) iValue;1480for (int i = kDigits; i < nDigits; i++) {1481lValue = lValue * 10L + (long) ((int) digits[i] - (int) '0');1482}1483double dValue = (double) lValue;1484exp = decExponent - nDigits;1485dValue *= SMALL_10_POW[exp];1486fValue = (float) dValue;1487return (isNegative) ? -fValue : fValue;14881489}1490//1491// Harder cases:1492// The sum of digits plus exponent is greater than1493// what we think we can do with one error.1494//1495// Start by approximating the right answer by,1496// naively, scaling by powers of 10.1497// Scaling uses doubles to avoid overflow/underflow.1498//1499double dValue = fValue;1500if (exp > 0) {1501if (decExponent > SINGLE_MAX_DECIMAL_EXPONENT + 1) {1502//1503// Lets face it. This is going to be1504// Infinity. Cut to the chase.1505//1506return (isNegative) ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;1507}1508if ((exp & 15) != 0) {1509dValue *= SMALL_10_POW[exp & 15];1510}1511if ((exp >>= 4) != 0) {1512int j;1513for (j = 0; exp > 0; j++, exp >>= 1) {1514if ((exp & 1) != 0) {1515dValue *= BIG_10_POW[j];1516}1517}1518}1519} else if (exp < 0) {1520exp = -exp;1521if (decExponent < SINGLE_MIN_DECIMAL_EXPONENT - 1) {1522//1523// Lets face it. This is going to be1524// zero. Cut to the chase.1525//1526return (isNegative) ? -0.0f : 0.0f;1527}1528if ((exp & 15) != 0) {1529dValue /= SMALL_10_POW[exp & 15];1530}1531if ((exp >>= 4) != 0) {1532int j;1533for (j = 0; exp > 0; j++, exp >>= 1) {1534if ((exp & 1) != 0) {1535dValue *= TINY_10_POW[j];1536}1537}1538}1539}1540fValue = Math.max(Float.MIN_VALUE, Math.min(Float.MAX_VALUE, (float) dValue));15411542//1543// fValue is now approximately the result.1544// The hard part is adjusting it, by comparison1545// with FDBigInteger arithmetic.1546// Formulate the EXACT big-number result as1547// bigD0 * 10^exp1548//1549if (nDigits > SINGLE_MAX_NDIGITS) {1550nDigits = SINGLE_MAX_NDIGITS + 1;1551digits[SINGLE_MAX_NDIGITS] = '1';1552}1553FDBigInteger bigD0 = new FDBigInteger(iValue, digits, kDigits, nDigits);1554exp = decExponent - nDigits;15551556int ieeeBits = Float.floatToRawIntBits(fValue); // IEEE-754 bits of float candidate1557final int B5 = Math.max(0, -exp); // powers of 5 in bigB, value is not modified inside correctionLoop1558final int D5 = Math.max(0, exp); // powers of 5 in bigD, value is not modified inside correctionLoop1559bigD0 = bigD0.multByPow52(D5, 0);1560bigD0.makeImmutable(); // prevent bigD0 modification inside correctionLoop1561FDBigInteger bigD = null;1562int prevD2 = 0;15631564correctionLoop:1565while (true) {1566// here ieeeBits can't be NaN, Infinity or zero1567int binexp = ieeeBits >>> SINGLE_EXP_SHIFT;1568int bigBbits = ieeeBits & FloatConsts.SIGNIF_BIT_MASK;1569if (binexp > 0) {1570bigBbits |= SINGLE_FRACT_HOB;1571} else { // Normalize denormalized numbers.1572assert bigBbits != 0 : bigBbits; // floatToBigInt(0.0)1573int leadingZeros = Integer.numberOfLeadingZeros(bigBbits);1574int shift = leadingZeros - (31 - SINGLE_EXP_SHIFT);1575bigBbits <<= shift;1576binexp = 1 - shift;1577}1578binexp -= FloatConsts.EXP_BIAS;1579int lowOrderZeros = Integer.numberOfTrailingZeros(bigBbits);1580bigBbits >>>= lowOrderZeros;1581final int bigIntExp = binexp - SINGLE_EXP_SHIFT + lowOrderZeros;1582final int bigIntNBits = SINGLE_EXP_SHIFT + 1 - lowOrderZeros;15831584//1585// Scale bigD, bigB appropriately for1586// big-integer operations.1587// Naively, we multiply by powers of ten1588// and powers of two. What we actually do1589// is keep track of the powers of 5 and1590// powers of 2 we would use, then factor out1591// common divisors before doing the work.1592//1593int B2 = B5; // powers of 2 in bigB1594int D2 = D5; // powers of 2 in bigD1595int Ulp2; // powers of 2 in halfUlp.1596if (bigIntExp >= 0) {1597B2 += bigIntExp;1598} else {1599D2 -= bigIntExp;1600}1601Ulp2 = B2;1602// shift bigB and bigD left by a number s. t.1603// halfUlp is still an integer.1604int hulpbias;1605if (binexp <= -FloatConsts.EXP_BIAS) {1606// This is going to be a denormalized number1607// (if not actually zero).1608// half an ULP is at 2^-(FloatConsts.EXP_BIAS+SINGLE_EXP_SHIFT+1)1609hulpbias = binexp + lowOrderZeros + FloatConsts.EXP_BIAS;1610} else {1611hulpbias = 1 + lowOrderZeros;1612}1613B2 += hulpbias;1614D2 += hulpbias;1615// if there are common factors of 2, we might just as well1616// factor them out, as they add nothing useful.1617int common2 = Math.min(B2, Math.min(D2, Ulp2));1618B2 -= common2;1619D2 -= common2;1620Ulp2 -= common2;1621// do multiplications by powers of 5 and 21622FDBigInteger bigB = FDBigInteger.valueOfMulPow52(bigBbits, B5, B2);1623if (bigD == null || prevD2 != D2) {1624bigD = bigD0.leftShift(D2);1625prevD2 = D2;1626}1627//1628// to recap:1629// bigB is the scaled-big-int version of our floating-point1630// candidate.1631// bigD is the scaled-big-int version of the exact value1632// as we understand it.1633// halfUlp is 1/2 an ulp of bigB, except for special cases1634// of exact powers of 21635//1636// the plan is to compare bigB with bigD, and if the difference1637// is less than halfUlp, then we're satisfied. Otherwise,1638// use the ratio of difference to halfUlp to calculate a fudge1639// factor to add to the floating value, then go 'round again.1640//1641FDBigInteger diff;1642int cmpResult;1643boolean overvalue;1644if ((cmpResult = bigB.cmp(bigD)) > 0) {1645overvalue = true; // our candidate is too big.1646diff = bigB.leftInplaceSub(bigD); // bigB is not user further - reuse1647if ((bigIntNBits == 1) && (bigIntExp > -FloatConsts.EXP_BIAS + 1)) {1648// candidate is a normalized exact power of 2 and1649// is too big (larger than Float.MIN_NORMAL). We will be subtracting.1650// For our purposes, ulp is the ulp of the1651// next smaller range.1652Ulp2 -= 1;1653if (Ulp2 < 0) {1654// rats. Cannot de-scale ulp this far.1655// must scale diff in other direction.1656Ulp2 = 0;1657diff = diff.leftShift(1);1658}1659}1660} else if (cmpResult < 0) {1661overvalue = false; // our candidate is too small.1662diff = bigD.rightInplaceSub(bigB); // bigB is not user further - reuse1663} else {1664// the candidate is exactly right!1665// this happens with surprising frequency1666break correctionLoop;1667}1668cmpResult = diff.cmpPow52(B5, Ulp2);1669if ((cmpResult) < 0) {1670// difference is small.1671// this is close enough1672break correctionLoop;1673} else if (cmpResult == 0) {1674// difference is exactly half an ULP1675// round to some other value maybe, then finish1676if ((ieeeBits & 1) != 0) { // half ties to even1677ieeeBits += overvalue ? -1 : 1; // nextDown or nextUp1678}1679break correctionLoop;1680} else {1681// difference is non-trivial.1682// could scale addend by ratio of difference to1683// halfUlp here, if we bothered to compute that difference.1684// Most of the time ( I hope ) it is about 1 anyway.1685ieeeBits += overvalue ? -1 : 1; // nextDown or nextUp1686if (ieeeBits == 0 || ieeeBits == FloatConsts.EXP_BIT_MASK) { // 0.0 or Float.POSITIVE_INFINITY1687break correctionLoop; // oops. Fell off end of range.1688}1689continue; // try again.1690}16911692}1693if (isNegative) {1694ieeeBits |= FloatConsts.SIGN_BIT_MASK;1695}1696return Float.intBitsToFloat(ieeeBits);1697}169816991700/**1701* All the positive powers of 10 that can be1702* represented exactly in double/float.1703*/1704private static final double[] SMALL_10_POW = {17051.0e0,17061.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5,17071.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10,17081.0e11, 1.0e12, 1.0e13, 1.0e14, 1.0e15,17091.0e16, 1.0e17, 1.0e18, 1.0e19, 1.0e20,17101.0e21, 1.0e221711};17121713private static final float[] SINGLE_SMALL_10_POW = {17141.0e0f,17151.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,17161.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f1717};17181719private static final double[] BIG_10_POW = {17201e16, 1e32, 1e64, 1e128, 1e256 };1721private static final double[] TINY_10_POW = {17221e-16, 1e-32, 1e-64, 1e-128, 1e-256 };17231724private static final int MAX_SMALL_TEN = SMALL_10_POW.length-1;1725private static final int SINGLE_MAX_SMALL_TEN = SINGLE_SMALL_10_POW.length-1;17261727}17281729/**1730* Returns a <code>BinaryToASCIIConverter</code> for a <code>double</code>.1731* The returned object is a <code>ThreadLocal</code> variable of this class.1732*1733* @param d The double precision value to convert.1734* @return The converter.1735*/1736public static BinaryToASCIIConverter getBinaryToASCIIConverter(double d) {1737return getBinaryToASCIIConverter(d, true);1738}17391740/**1741* Returns a <code>BinaryToASCIIConverter</code> for a <code>double</code>.1742* The returned object is a <code>ThreadLocal</code> variable of this class.1743*1744* @param d The double precision value to convert.1745* @param isCompatibleFormat1746* @return The converter.1747*/1748static BinaryToASCIIConverter getBinaryToASCIIConverter(double d, boolean isCompatibleFormat) {1749long dBits = Double.doubleToRawLongBits(d);1750boolean isNegative = (dBits&DoubleConsts.SIGN_BIT_MASK) != 0; // discover sign1751long fractBits = dBits & DoubleConsts.SIGNIF_BIT_MASK;1752int binExp = (int)( (dBits&DoubleConsts.EXP_BIT_MASK) >> EXP_SHIFT );1753// Discover obvious special cases of NaN and Infinity.1754if ( binExp == (int)(DoubleConsts.EXP_BIT_MASK>>EXP_SHIFT) ) {1755if ( fractBits == 0L ){1756return isNegative ? B2AC_NEGATIVE_INFINITY : B2AC_POSITIVE_INFINITY;1757} else {1758return B2AC_NOT_A_NUMBER;1759}1760}1761// Finish unpacking1762// Normalize denormalized numbers.1763// Insert assumed high-order bit for normalized numbers.1764// Subtract exponent bias.1765int nSignificantBits;1766if ( binExp == 0 ){1767if ( fractBits == 0L ){1768// not a denorm, just a 0!1769return isNegative ? B2AC_NEGATIVE_ZERO : B2AC_POSITIVE_ZERO;1770}1771int leadingZeros = Long.numberOfLeadingZeros(fractBits);1772int shift = leadingZeros-(63-EXP_SHIFT);1773fractBits <<= shift;1774binExp = 1 - shift;1775nSignificantBits = 64-leadingZeros; // recall binExp is - shift count.1776} else {1777fractBits |= FRACT_HOB;1778nSignificantBits = EXP_SHIFT+1;1779}1780binExp -= DoubleConsts.EXP_BIAS;1781BinaryToASCIIBuffer buf = getBinaryToASCIIBuffer();1782buf.setSign(isNegative);1783// call the routine that actually does all the hard work.1784buf.dtoa(binExp, fractBits, nSignificantBits, isCompatibleFormat);1785return buf;1786}17871788private static BinaryToASCIIConverter getBinaryToASCIIConverter(float f) {1789int fBits = Float.floatToRawIntBits( f );1790boolean isNegative = (fBits&FloatConsts.SIGN_BIT_MASK) != 0;1791int fractBits = fBits&FloatConsts.SIGNIF_BIT_MASK;1792int binExp = (fBits&FloatConsts.EXP_BIT_MASK) >> SINGLE_EXP_SHIFT;1793// Discover obvious special cases of NaN and Infinity.1794if ( binExp == (FloatConsts.EXP_BIT_MASK>>SINGLE_EXP_SHIFT) ) {1795if ( fractBits == 0L ){1796return isNegative ? B2AC_NEGATIVE_INFINITY : B2AC_POSITIVE_INFINITY;1797} else {1798return B2AC_NOT_A_NUMBER;1799}1800}1801// Finish unpacking1802// Normalize denormalized numbers.1803// Insert assumed high-order bit for normalized numbers.1804// Subtract exponent bias.1805int nSignificantBits;1806if ( binExp == 0 ){1807if ( fractBits == 0 ){1808// not a denorm, just a 0!1809return isNegative ? B2AC_NEGATIVE_ZERO : B2AC_POSITIVE_ZERO;1810}1811int leadingZeros = Integer.numberOfLeadingZeros(fractBits);1812int shift = leadingZeros-(31-SINGLE_EXP_SHIFT);1813fractBits <<= shift;1814binExp = 1 - shift;1815nSignificantBits = 32 - leadingZeros; // recall binExp is - shift count.1816} else {1817fractBits |= SINGLE_FRACT_HOB;1818nSignificantBits = SINGLE_EXP_SHIFT+1;1819}1820binExp -= FloatConsts.EXP_BIAS;1821BinaryToASCIIBuffer buf = getBinaryToASCIIBuffer();1822buf.setSign(isNegative);1823// call the routine that actually does all the hard work.1824buf.dtoa(binExp, ((long)fractBits)<<(EXP_SHIFT-SINGLE_EXP_SHIFT), nSignificantBits, true);1825return buf;1826}18271828@SuppressWarnings("fallthrough")1829static ASCIIToBinaryConverter readJavaFormatString( String in ) throws NumberFormatException {1830boolean isNegative = false;1831boolean signSeen = false;1832int decExp;1833char c;18341835parseNumber:1836try{1837in = in.trim(); // don't fool around with white space.1838// throws NullPointerException if null1839int len = in.length();1840if ( len == 0 ) {1841throw new NumberFormatException("empty String");1842}1843int i = 0;1844switch (in.charAt(i)){1845case '-':1846isNegative = true;1847//FALLTHROUGH1848case '+':1849i++;1850signSeen = true;1851}1852c = in.charAt(i);1853if(c == 'N') { // Check for NaN1854if((len-i)==NAN_LENGTH && in.indexOf(NAN_REP,i)==i) {1855return A2BC_NOT_A_NUMBER;1856}1857// something went wrong, throw exception1858break parseNumber;1859} else if(c == 'I') { // Check for Infinity strings1860if((len-i)==INFINITY_LENGTH && in.indexOf(INFINITY_REP,i)==i) {1861return isNegative? A2BC_NEGATIVE_INFINITY : A2BC_POSITIVE_INFINITY;1862}1863// something went wrong, throw exception1864break parseNumber;1865} else if (c == '0') { // check for hexadecimal floating-point number1866if (len > i+1 ) {1867char ch = in.charAt(i+1);1868if (ch == 'x' || ch == 'X' ) { // possible hex string1869return parseHexString(in);1870}1871}1872} // look for and process decimal floating-point string18731874char[] digits = new char[ len ];1875boolean decSeen = false;1876int nDigits = 0;1877int decPt = 0;1878int nLeadZero = 0;1879int nTrailZero = 0;18801881skipLeadingZerosLoop:1882while (i < len) {1883c = in.charAt(i);1884if (c == '0') {1885nLeadZero++;1886} else if (c == '.') {1887if (decSeen) {1888// already saw one ., this is the 2nd.1889throw new NumberFormatException("multiple points");1890}1891decPt = i;1892if (signSeen) {1893decPt -= 1;1894}1895decSeen = true;1896} else {1897break skipLeadingZerosLoop;1898}1899i++;1900}1901digitLoop:1902while (i < len) {1903c = in.charAt(i);1904if (c >= '1' && c <= '9') {1905digits[nDigits++] = c;1906nTrailZero = 0;1907} else if (c == '0') {1908digits[nDigits++] = c;1909nTrailZero++;1910} else if (c == '.') {1911if (decSeen) {1912// already saw one ., this is the 2nd.1913throw new NumberFormatException("multiple points");1914}1915decPt = i;1916if (signSeen) {1917decPt -= 1;1918}1919decSeen = true;1920} else {1921break digitLoop;1922}1923i++;1924}1925nDigits -=nTrailZero;1926//1927// At this point, we've scanned all the digits and decimal1928// point we're going to see. Trim off leading and trailing1929// zeros, which will just confuse us later, and adjust1930// our initial decimal exponent accordingly.1931// To review:1932// we have seen i total characters.1933// nLeadZero of them were zeros before any other digits.1934// nTrailZero of them were zeros after any other digits.1935// if ( decSeen ), then a . was seen after decPt characters1936// ( including leading zeros which have been discarded )1937// nDigits characters were neither lead nor trailing1938// zeros, nor point1939//1940//1941// special hack: if we saw no non-zero digits, then the1942// answer is zero!1943// Unfortunately, we feel honor-bound to keep parsing!1944//1945boolean isZero = (nDigits == 0);1946if ( isZero && nLeadZero == 0 ){1947// we saw NO DIGITS AT ALL,1948// not even a crummy 0!1949// this is not allowed.1950break parseNumber; // go throw exception1951}1952//1953// Our initial exponent is decPt, adjusted by the number of1954// discarded zeros. Or, if there was no decPt,1955// then its just nDigits adjusted by discarded trailing zeros.1956//1957if ( decSeen ){1958decExp = decPt - nLeadZero;1959} else {1960decExp = nDigits + nTrailZero;1961}19621963//1964// Look for 'e' or 'E' and an optionally signed integer.1965//1966if ( (i < len) && (((c = in.charAt(i) )=='e') || (c == 'E') ) ){1967int expSign = 1;1968int expVal = 0;1969int reallyBig = Integer.MAX_VALUE / 10;1970boolean expOverflow = false;1971switch( in.charAt(++i) ){1972case '-':1973expSign = -1;1974//FALLTHROUGH1975case '+':1976i++;1977}1978int expAt = i;1979expLoop:1980while ( i < len ){1981if ( expVal >= reallyBig ){1982// the next character will cause integer1983// overflow.1984expOverflow = true;1985}1986c = in.charAt(i++);1987if(c>='0' && c<='9') {1988expVal = expVal*10 + ( (int)c - (int)'0' );1989} else {1990i--; // back up.1991break expLoop; // stop parsing exponent.1992}1993}1994int expLimit = BIG_DECIMAL_EXPONENT + nDigits + nTrailZero;1995if (expOverflow || (expVal > expLimit)) {1996// There is still a chance that the exponent will be safe to1997// use: if it would eventually decrease due to a negative1998// decExp, and that number is below the limit. We check for1999// that here.2000if (!expOverflow && (expSign == 1 && decExp < 0)2001&& (expVal + decExp) < expLimit) {2002// Cannot overflow: adding a positive and negative number.2003decExp += expVal;2004} else {2005//2006// The intent here is to end up with2007// infinity or zero, as appropriate.2008// The reason for yielding such a small decExponent,2009// rather than something intuitive such as2010// expSign*Integer.MAX_VALUE, is that this value2011// is subject to further manipulation in2012// doubleValue() and floatValue(), and I don't want2013// it to be able to cause overflow there!2014// (The only way we can get into trouble here is for2015// really outrageous nDigits+nTrailZero, such as 22016// billion.)2017//2018decExp = expSign * expLimit;2019}2020} else {2021// this should not overflow, since we tested2022// for expVal > (MAX+N), where N >= abs(decExp)2023decExp = decExp + expSign*expVal;2024}20252026// if we saw something not a digit ( or end of string )2027// after the [Ee][+-], without seeing any digits at all2028// this is certainly an error. If we saw some digits,2029// but then some trailing garbage, that might be ok.2030// so we just fall through in that case.2031// HUMBUG2032if ( i == expAt ) {2033break parseNumber; // certainly bad2034}2035}2036//2037// We parsed everything we could.2038// If there are leftovers, then this is not good input!2039//2040if ( i < len &&2041((i != len - 1) ||2042(in.charAt(i) != 'f' &&2043in.charAt(i) != 'F' &&2044in.charAt(i) != 'd' &&2045in.charAt(i) != 'D'))) {2046break parseNumber; // go throw exception2047}2048if(isZero) {2049return isNegative ? A2BC_NEGATIVE_ZERO : A2BC_POSITIVE_ZERO;2050}2051return new ASCIIToBinaryBuffer(isNegative, decExp, digits, nDigits);2052} catch ( StringIndexOutOfBoundsException e ){ }2053throw new NumberFormatException("For input string: \"" + in + "\"");2054}20552056private static class HexFloatPattern {2057/**2058* Grammar is compatible with hexadecimal floating-point constants2059* described in section 6.4.4.2 of the C99 specification.2060*/2061private static final Pattern VALUE = Pattern.compile(2062//1 234 56 7 8 92063"([-+])?0[xX](((\\p{XDigit}+)\\.?)|((\\p{XDigit}*)\\.(\\p{XDigit}+)))[pP]([-+])?(\\p{Digit}+)[fFdD]?"2064);2065}20662067/**2068* Converts string s to a suitable floating decimal; uses the2069* double constructor and sets the roundDir variable appropriately2070* in case the value is later converted to a float.2071*2072* @param s The <code>String</code> to parse.2073*/2074static ASCIIToBinaryConverter parseHexString(String s) {2075// Verify string is a member of the hexadecimal floating-point2076// string language.2077Matcher m = HexFloatPattern.VALUE.matcher(s);2078boolean validInput = m.matches();2079if (!validInput) {2080// Input does not match pattern2081throw new NumberFormatException("For input string: \"" + s + "\"");2082} else { // validInput2083//2084// We must isolate the sign, significand, and exponent2085// fields. The sign value is straightforward. Since2086// floating-point numbers are stored with a normalized2087// representation, the significand and exponent are2088// interrelated.2089//2090// After extracting the sign, we normalized the2091// significand as a hexadecimal value, calculating an2092// exponent adjust for any shifts made during2093// normalization. If the significand is zero, the2094// exponent doesn't need to be examined since the output2095// will be zero.2096//2097// Next the exponent in the input string is extracted.2098// Afterwards, the significand is normalized as a *binary*2099// value and the input value's normalized exponent can be2100// computed. The significand bits are copied into a2101// double significand; if the string has more logical bits2102// than can fit in a double, the extra bits affect the2103// round and sticky bits which are used to round the final2104// value.2105//2106// Extract significand sign2107String group1 = m.group(1);2108boolean isNegative = ((group1 != null) && group1.equals("-"));21092110// Extract Significand magnitude2111//2112// Based on the form of the significand, calculate how the2113// binary exponent needs to be adjusted to create a2114// normalized//hexadecimal* floating-point number; that2115// is, a number where there is one nonzero hex digit to2116// the left of the (hexa)decimal point. Since we are2117// adjusting a binary, not hexadecimal exponent, the2118// exponent is adjusted by a multiple of 4.2119//2120// There are a number of significand scenarios to consider;2121// letters are used in indicate nonzero digits:2122//2123// 1. 000xxxx => x.xxx normalized2124// increase exponent by (number of x's - 1)*42125//2126// 2. 000xxx.yyyy => x.xxyyyy normalized2127// increase exponent by (number of x's - 1)*42128//2129// 3. .000yyy => y.yy normalized2130// decrease exponent by (number of zeros + 1)*42131//2132// 4. 000.00000yyy => y.yy normalized2133// decrease exponent by (number of zeros to right of point + 1)*42134//2135// If the significand is exactly zero, return a properly2136// signed zero.2137//21382139String significandString;2140int signifLength;2141int exponentAdjust;2142{2143int leftDigits = 0; // number of meaningful digits to2144// left of "decimal" point2145// (leading zeros stripped)2146int rightDigits = 0; // number of digits to right of2147// "decimal" point; leading zeros2148// must always be accounted for2149//2150// The significand is made up of either2151//2152// 1. group 4 entirely (integer portion only)2153//2154// OR2155//2156// 2. the fractional portion from group 7 plus any2157// (optional) integer portions from group 6.2158//2159String group4;2160if ((group4 = m.group(4)) != null) { // Integer-only significand2161// Leading zeros never matter on the integer portion2162significandString = stripLeadingZeros(group4);2163leftDigits = significandString.length();2164} else {2165// Group 6 is the optional integer; leading zeros2166// never matter on the integer portion2167String group6 = stripLeadingZeros(m.group(6));2168leftDigits = group6.length();21692170// fraction2171String group7 = m.group(7);2172rightDigits = group7.length();21732174// Turn "integer.fraction" into "integer"+"fraction"2175significandString =2176((group6 == null) ? "" : group6) + // is the null2177// check necessary?2178group7;2179}21802181significandString = stripLeadingZeros(significandString);2182signifLength = significandString.length();21832184//2185// Adjust exponent as described above2186//2187if (leftDigits >= 1) { // Cases 1 and 22188exponentAdjust = 4 * (leftDigits - 1);2189} else { // Cases 3 and 42190exponentAdjust = -4 * (rightDigits - signifLength + 1);2191}21922193// If the significand is zero, the exponent doesn't2194// matter; return a properly signed zero.21952196if (signifLength == 0) { // Only zeros in input2197return isNegative ? A2BC_NEGATIVE_ZERO : A2BC_POSITIVE_ZERO;2198}2199}22002201// Extract Exponent2202//2203// Use an int to read in the exponent value; this should2204// provide more than sufficient range for non-contrived2205// inputs. If reading the exponent in as an int does2206// overflow, examine the sign of the exponent and2207// significand to determine what to do.2208//2209String group8 = m.group(8);2210boolean positiveExponent = (group8 == null) || group8.equals("+");2211long unsignedRawExponent;2212try {2213unsignedRawExponent = Integer.parseInt(m.group(9));2214}2215catch (NumberFormatException e) {2216// At this point, we know the exponent is2217// syntactically well-formed as a sequence of2218// digits. Therefore, if an NumberFormatException2219// is thrown, it must be due to overflowing int's2220// range. Also, at this point, we have already2221// checked for a zero significand. Thus the signs2222// of the exponent and significand determine the2223// final result:2224//2225// significand2226// + -2227// exponent + +infinity -infinity2228// - +0.0 -0.02229return isNegative ?2230(positiveExponent ? A2BC_NEGATIVE_INFINITY : A2BC_NEGATIVE_ZERO)2231: (positiveExponent ? A2BC_POSITIVE_INFINITY : A2BC_POSITIVE_ZERO);22322233}22342235long rawExponent =2236(positiveExponent ? 1L : -1L) * // exponent sign2237unsignedRawExponent; // exponent magnitude22382239// Calculate partially adjusted exponent2240long exponent = rawExponent + exponentAdjust;22412242// Starting copying non-zero bits into proper position in2243// a long; copy explicit bit too; this will be masked2244// later for normal values.22452246boolean round = false;2247boolean sticky = false;2248int nextShift;2249long significand = 0L;2250// First iteration is different, since we only copy2251// from the leading significand bit; one more exponent2252// adjust will be needed...22532254// IMPORTANT: make leadingDigit a long to avoid2255// surprising shift semantics!2256long leadingDigit = getHexDigit(significandString, 0);22572258//2259// Left shift the leading digit (53 - (bit position of2260// leading 1 in digit)); this sets the top bit of the2261// significand to 1. The nextShift value is adjusted2262// to take into account the number of bit positions of2263// the leadingDigit actually used. Finally, the2264// exponent is adjusted to normalize the significand2265// as a binary value, not just a hex value.2266//2267if (leadingDigit == 1) {2268significand |= leadingDigit << 52;2269nextShift = 52 - 4;2270// exponent += 02271} else if (leadingDigit <= 3) { // [2, 3]2272significand |= leadingDigit << 51;2273nextShift = 52 - 5;2274exponent += 1;2275} else if (leadingDigit <= 7) { // [4, 7]2276significand |= leadingDigit << 50;2277nextShift = 52 - 6;2278exponent += 2;2279} else if (leadingDigit <= 15) { // [8, f]2280significand |= leadingDigit << 49;2281nextShift = 52 - 7;2282exponent += 3;2283} else {2284throw new AssertionError("Result from digit conversion too large!");2285}2286// The preceding if-else could be replaced by a single2287// code block based on the high-order bit set in2288// leadingDigit. Given leadingOnePosition,22892290// significand |= leadingDigit << (SIGNIFICAND_WIDTH - leadingOnePosition);2291// nextShift = 52 - (3 + leadingOnePosition);2292// exponent += (leadingOnePosition-1);22932294//2295// Now the exponent variable is equal to the normalized2296// binary exponent. Code below will make representation2297// adjustments if the exponent is incremented after2298// rounding (includes overflows to infinity) or if the2299// result is subnormal.2300//23012302// Copy digit into significand until the significand can't2303// hold another full hex digit or there are no more input2304// hex digits.2305int i = 0;2306for (i = 1;2307i < signifLength && nextShift >= 0;2308i++) {2309long currentDigit = getHexDigit(significandString, i);2310significand |= (currentDigit << nextShift);2311nextShift -= 4;2312}23132314// After the above loop, the bulk of the string is copied.2315// Now, we must copy any partial hex digits into the2316// significand AND compute the round bit and start computing2317// sticky bit.23182319if (i < signifLength) { // at least one hex input digit exists2320long currentDigit = getHexDigit(significandString, i);23212322// from nextShift, figure out how many bits need2323// to be copied, if any2324switch (nextShift) { // must be negative2325case -1:2326// three bits need to be copied in; can2327// set round bit2328significand |= ((currentDigit & 0xEL) >> 1);2329round = (currentDigit & 0x1L) != 0L;2330break;23312332case -2:2333// two bits need to be copied in; can2334// set round and start sticky2335significand |= ((currentDigit & 0xCL) >> 2);2336round = (currentDigit & 0x2L) != 0L;2337sticky = (currentDigit & 0x1L) != 0;2338break;23392340case -3:2341// one bit needs to be copied in2342significand |= ((currentDigit & 0x8L) >> 3);2343// Now set round and start sticky, if possible2344round = (currentDigit & 0x4L) != 0L;2345sticky = (currentDigit & 0x3L) != 0;2346break;23472348case -4:2349// all bits copied into significand; set2350// round and start sticky2351round = ((currentDigit & 0x8L) != 0); // is top bit set?2352// nonzeros in three low order bits?2353sticky = (currentDigit & 0x7L) != 0;2354break;23552356default:2357throw new AssertionError("Unexpected shift distance remainder.");2358// break;2359}23602361// Round is set; sticky might be set.23622363// For the sticky bit, it suffices to check the2364// current digit and test for any nonzero digits in2365// the remaining unprocessed input.2366i++;2367while (i < signifLength && !sticky) {2368currentDigit = getHexDigit(significandString, i);2369sticky = sticky || (currentDigit != 0);2370i++;2371}23722373}2374// else all of string was seen, round and sticky are2375// correct as false.23762377// Float calculations2378int floatBits = isNegative ? FloatConsts.SIGN_BIT_MASK : 0;2379if (exponent >= Float.MIN_EXPONENT) {2380if (exponent > Float.MAX_EXPONENT) {2381// Float.POSITIVE_INFINITY2382floatBits |= FloatConsts.EXP_BIT_MASK;2383} else {2384int threshShift = DoubleConsts.SIGNIFICAND_WIDTH - FloatConsts.SIGNIFICAND_WIDTH - 1;2385boolean floatSticky = (significand & ((1L << threshShift) - 1)) != 0 || round || sticky;2386int iValue = (int) (significand >>> threshShift);2387if ((iValue & 3) != 1 || floatSticky) {2388iValue++;2389}2390floatBits |= (((((int) exponent) + (FloatConsts.EXP_BIAS - 1))) << SINGLE_EXP_SHIFT) + (iValue >> 1);2391}2392} else {2393if (exponent < FloatConsts.MIN_SUB_EXPONENT - 1) {2394// 02395} else {2396// exponent == -127 ==> threshShift = 53 - 2 + (-149) - (-127) = 53 - 242397int threshShift = (int) ((DoubleConsts.SIGNIFICAND_WIDTH - 2 + FloatConsts.MIN_SUB_EXPONENT) - exponent);2398assert threshShift >= DoubleConsts.SIGNIFICAND_WIDTH - FloatConsts.SIGNIFICAND_WIDTH;2399assert threshShift < DoubleConsts.SIGNIFICAND_WIDTH;2400boolean floatSticky = (significand & ((1L << threshShift) - 1)) != 0 || round || sticky;2401int iValue = (int) (significand >>> threshShift);2402if ((iValue & 3) != 1 || floatSticky) {2403iValue++;2404}2405floatBits |= iValue >> 1;2406}2407}2408float fValue = Float.intBitsToFloat(floatBits);24092410// Check for overflow and update exponent accordingly.2411if (exponent > Double.MAX_EXPONENT) { // Infinite result2412// overflow to properly signed infinity2413return isNegative ? A2BC_NEGATIVE_INFINITY : A2BC_POSITIVE_INFINITY;2414} else { // Finite return value2415if (exponent <= Double.MAX_EXPONENT && // (Usually) normal result2416exponent >= Double.MIN_EXPONENT) {24172418// The result returned in this block cannot be a2419// zero or subnormal; however after the2420// significand is adjusted from rounding, we could2421// still overflow in infinity.24222423// AND exponent bits into significand; if the2424// significand is incremented and overflows from2425// rounding, this combination will update the2426// exponent correctly, even in the case of2427// Double.MAX_VALUE overflowing to infinity.24282429significand = ((( exponent +2430(long) DoubleConsts.EXP_BIAS) <<2431(DoubleConsts.SIGNIFICAND_WIDTH - 1))2432& DoubleConsts.EXP_BIT_MASK) |2433(DoubleConsts.SIGNIF_BIT_MASK & significand);24342435} else { // Subnormal or zero2436// (exponent < Double.MIN_EXPONENT)24372438if (exponent < (DoubleConsts.MIN_SUB_EXPONENT - 1)) {2439// No way to round back to nonzero value2440// regardless of significand if the exponent is2441// less than -1075.2442return isNegative ? A2BC_NEGATIVE_ZERO : A2BC_POSITIVE_ZERO;2443} else { // -1075 <= exponent <= MIN_EXPONENT -1 = -10232444//2445// Find bit position to round to; recompute2446// round and sticky bits, and shift2447// significand right appropriately.2448//24492450sticky = sticky || round;2451round = false;24522453// Number of bits of significand to preserve is2454// exponent - abs_min_exp +12455// check:2456// -1075 +1074 + 1 = 02457// -1023 +1074 + 1 = 5224582459int bitsDiscarded = 53 -2460((int) exponent - DoubleConsts.MIN_SUB_EXPONENT + 1);2461assert bitsDiscarded >= 1 && bitsDiscarded <= 53;24622463// What to do here:2464// First, isolate the new round bit2465round = (significand & (1L << (bitsDiscarded - 1))) != 0L;2466if (bitsDiscarded > 1) {2467// create mask to update sticky bits; low2468// order bitsDiscarded bits should be 12469long mask = ~((~0L) << (bitsDiscarded - 1));2470sticky = sticky || ((significand & mask) != 0L);2471}24722473// Now, discard the bits2474significand = significand >> bitsDiscarded;24752476significand = ((((long) (Double.MIN_EXPONENT - 1) + // subnorm exp.2477(long) DoubleConsts.EXP_BIAS) <<2478(DoubleConsts.SIGNIFICAND_WIDTH - 1))2479& DoubleConsts.EXP_BIT_MASK) |2480(DoubleConsts.SIGNIF_BIT_MASK & significand);2481}2482}24832484// The significand variable now contains the currently2485// appropriate exponent bits too.24862487//2488// Determine if significand should be incremented;2489// making this determination depends on the least2490// significant bit and the round and sticky bits.2491//2492// Round to nearest even rounding table, adapted from2493// table 4.7 in "Computer Arithmetic" by IsraelKoren.2494// The digit to the left of the "decimal" point is the2495// least significant bit, the digits to the right of2496// the point are the round and sticky bits2497//2498// Number Round(x)2499// x0.00 x0.2500// x0.01 x0.2501// x0.10 x0.2502// x0.11 x1. = x0. +12503// x1.00 x1.2504// x1.01 x1.2505// x1.10 x1. + 12506// x1.11 x1. + 12507//2508boolean leastZero = ((significand & 1L) == 0L);2509if ((leastZero && round && sticky) ||2510((!leastZero) && round)) {2511significand++;2512}25132514double value = isNegative ?2515Double.longBitsToDouble(significand | DoubleConsts.SIGN_BIT_MASK) :2516Double.longBitsToDouble(significand );25172518return new PreparedASCIIToBinaryBuffer(value, fValue);2519}2520}2521}25222523/**2524* Returns <code>s</code> with any leading zeros removed.2525*/2526static String stripLeadingZeros(String s) {2527if(!s.isEmpty() && s.charAt(0)=='0') {2528for(int i=1; i<s.length(); i++) {2529if(s.charAt(i)!='0') {2530return s.substring(i);2531}2532}2533return "";2534}2535return s;2536}25372538/**2539* Extracts a hexadecimal digit from position <code>position</code>2540* of string <code>s</code>.2541*/2542static int getHexDigit(String s, int position) {2543int value = Character.digit(s.charAt(position), 16);2544if (value <= -1 || value >= 16) {2545throw new AssertionError("Unexpected failure of digit conversion of " +2546s.charAt(position));2547}2548return value;2549}2550}255125522553