Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/sun/misc/FloatingDecimal/OldFloatingDecimalForTest.java
38839 views
/*1* Copyright (c) 1996, 2013, 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.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223//package sun.misc;2425import sun.misc.DoubleConsts;26import sun.misc.FloatConsts;27import java.util.regex.*;2829public class OldFloatingDecimalForTest{30boolean isExceptional;31boolean isNegative;32int decExponent;33char digits[];34int nDigits;35int bigIntExp;36int bigIntNBits;37boolean mustSetRoundDir = false;38boolean fromHex = false;39int roundDir = 0; // set by doubleValue4041/*42* The fields below provides additional information about the result of43* the binary to decimal digits conversion done in dtoa() and roundup()44* methods. They are changed if needed by those two methods.45*/4647// True if the dtoa() binary to decimal conversion was exact.48boolean exactDecimalConversion = false;4950// True if the result of the binary to decimal conversion was rounded-up51// at the end of the conversion process, i.e. roundUp() method was called.52boolean decimalDigitsRoundedUp = false;5354private OldFloatingDecimalForTest( boolean negSign, int decExponent, char []digits, int n, boolean e )55{56isNegative = negSign;57isExceptional = e;58this.decExponent = decExponent;59this.digits = digits;60this.nDigits = n;61}6263/*64* Constants of the implementation65* Most are IEEE-754 related.66* (There are more really boring constants at the end.)67*/68static final long signMask = 0x8000000000000000L;69static final long expMask = 0x7ff0000000000000L;70static final long fractMask= ~(signMask|expMask);71static final int expShift = 52;72static final int expBias = 1023;73static final long fractHOB = ( 1L<<expShift ); // assumed High-Order bit74static final long expOne = ((long)expBias)<<expShift; // exponent of 1.075static final int maxSmallBinExp = 62;76static final int minSmallBinExp = -( 63 / 3 );77static final int maxDecimalDigits = 15;78static final int maxDecimalExponent = 308;79static final int minDecimalExponent = -324;80static final int bigDecimalExponent = 324; // i.e. abs(minDecimalExponent)8182static final long highbyte = 0xff00000000000000L;83static final long highbit = 0x8000000000000000L;84static final long lowbytes = ~highbyte;8586static final int singleSignMask = 0x80000000;87static final int singleExpMask = 0x7f800000;88static final int singleFractMask = ~(singleSignMask|singleExpMask);89static final int singleExpShift = 23;90static final int singleFractHOB = 1<<singleExpShift;91static final int singleExpBias = 127;92static final int singleMaxDecimalDigits = 7;93static final int singleMaxDecimalExponent = 38;94static final int singleMinDecimalExponent = -45;9596static final int intDecimalDigits = 9;979899/*100* count number of bits from high-order 1 bit to low-order 1 bit,101* inclusive.102*/103private static int104countBits( long v ){105//106// the strategy is to shift until we get a non-zero sign bit107// then shift until we have no bits left, counting the difference.108// we do byte shifting as a hack. Hope it helps.109//110if ( v == 0L ) return 0;111112while ( ( v & highbyte ) == 0L ){113v <<= 8;114}115while ( v > 0L ) { // i.e. while ((v&highbit) == 0L )116v <<= 1;117}118119int n = 0;120while (( v & lowbytes ) != 0L ){121v <<= 8;122n += 8;123}124while ( v != 0L ){125v <<= 1;126n += 1;127}128return n;129}130131/*132* Keep big powers of 5 handy for future reference.133*/134private static OldFDBigIntForTest b5p[];135136private static synchronized OldFDBigIntForTest137big5pow( int p ){138assert p >= 0 : p; // negative power of 5139if ( b5p == null ){140b5p = new OldFDBigIntForTest[ p+1 ];141}else if (b5p.length <= p ){142OldFDBigIntForTest t[] = new OldFDBigIntForTest[ p+1 ];143System.arraycopy( b5p, 0, t, 0, b5p.length );144b5p = t;145}146if ( b5p[p] != null )147return b5p[p];148else if ( p < small5pow.length )149return b5p[p] = new OldFDBigIntForTest( small5pow[p] );150else if ( p < long5pow.length )151return b5p[p] = new OldFDBigIntForTest( long5pow[p] );152else {153// construct the value.154// recursively.155int q, r;156// in order to compute 5^p,157// compute its square root, 5^(p/2) and square.158// or, let q = p / 2, r = p -q, then159// 5^p = 5^(q+r) = 5^q * 5^r160q = p >> 1;161r = p - q;162OldFDBigIntForTest bigq = b5p[q];163if ( bigq == null )164bigq = big5pow ( q );165if ( r < small5pow.length ){166return (b5p[p] = bigq.mult( small5pow[r] ) );167}else{168OldFDBigIntForTest bigr = b5p[ r ];169if ( bigr == null )170bigr = big5pow( r );171return (b5p[p] = bigq.mult( bigr ) );172}173}174}175176//177// a common operation178//179private static OldFDBigIntForTest180multPow52( OldFDBigIntForTest v, int p5, int p2 ){181if ( p5 != 0 ){182if ( p5 < small5pow.length ){183v = v.mult( small5pow[p5] );184} else {185v = v.mult( big5pow( p5 ) );186}187}188if ( p2 != 0 ){189v.lshiftMe( p2 );190}191return v;192}193194//195// another common operation196//197private static OldFDBigIntForTest198constructPow52( int p5, int p2 ){199OldFDBigIntForTest v = new OldFDBigIntForTest( big5pow( p5 ) );200if ( p2 != 0 ){201v.lshiftMe( p2 );202}203return v;204}205206/*207* Make a floating double into a OldFDBigIntForTest.208* This could also be structured as a OldFDBigIntForTest209* constructor, but we'd have to build a lot of knowledge210* about floating-point representation into it, and we don't want to.211*212* AS A SIDE EFFECT, THIS METHOD WILL SET THE INSTANCE VARIABLES213* bigIntExp and bigIntNBits214*215*/216private OldFDBigIntForTest217doubleToBigInt( double dval ){218long lbits = Double.doubleToLongBits( dval ) & ~signMask;219int binexp = (int)(lbits >>> expShift);220lbits &= fractMask;221if ( binexp > 0 ){222lbits |= fractHOB;223} else {224assert lbits != 0L : lbits; // doubleToBigInt(0.0)225binexp +=1;226while ( (lbits & fractHOB ) == 0L){227lbits <<= 1;228binexp -= 1;229}230}231binexp -= expBias;232int nbits = countBits( lbits );233/*234* We now know where the high-order 1 bit is,235* and we know how many there are.236*/237int lowOrderZeros = expShift+1-nbits;238lbits >>>= lowOrderZeros;239240bigIntExp = binexp+1-nbits;241bigIntNBits = nbits;242return new OldFDBigIntForTest( lbits );243}244245/*246* Compute a number that is the ULP of the given value,247* for purposes of addition/subtraction. Generally easy.248* More difficult if subtracting and the argument249* is a normalized a power of 2, as the ULP changes at these points.250*/251private static double ulp( double dval, boolean subtracting ){252long lbits = Double.doubleToLongBits( dval ) & ~signMask;253int binexp = (int)(lbits >>> expShift);254double ulpval;255if ( subtracting && ( binexp >= expShift ) && ((lbits&fractMask) == 0L) ){256// for subtraction from normalized, powers of 2,257// use next-smaller exponent258binexp -= 1;259}260if ( binexp > expShift ){261ulpval = Double.longBitsToDouble( ((long)(binexp-expShift))<<expShift );262} else if ( binexp == 0 ){263ulpval = Double.MIN_VALUE;264} else {265ulpval = Double.longBitsToDouble( 1L<<(binexp-1) );266}267if ( subtracting ) ulpval = - ulpval;268269return ulpval;270}271272/*273* Round a double to a float.274* In addition to the fraction bits of the double,275* look at the class instance variable roundDir,276* which should help us avoid double-rounding error.277* roundDir was set in hardValueOf if the estimate was278* close enough, but not exact. It tells us which direction279* of rounding is preferred.280*/281float282stickyRound( double dval ){283long lbits = Double.doubleToLongBits( dval );284long binexp = lbits & expMask;285if ( binexp == 0L || binexp == expMask ){286// what we have here is special.287// don't worry, the right thing will happen.288return (float) dval;289}290lbits += (long)roundDir; // hack-o-matic.291return (float)Double.longBitsToDouble( lbits );292}293294295/*296* This is the easy subcase --297* all the significant bits, after scaling, are held in lvalue.298* negSign and decExponent tell us what processing and scaling299* has already been done. Exceptional cases have already been300* stripped out.301* In particular:302* lvalue is a finite number (not Inf, nor NaN)303* lvalue > 0L (not zero, nor negative).304*305* The only reason that we develop the digits here, rather than306* calling on Long.toString() is that we can do it a little faster,307* and besides want to treat trailing 0s specially. If Long.toString308* changes, we should re-evaluate this strategy!309*/310private void311developLongDigits( int decExponent, long lvalue, long insignificant ){312char digits[];313int ndigits;314int digitno;315int c;316//317// Discard non-significant low-order bits, while rounding,318// up to insignificant value.319int i;320for ( i = 0; insignificant >= 10L; i++ )321insignificant /= 10L;322if ( i != 0 ){323long pow10 = long5pow[i] << i; // 10^i == 5^i * 2^i;324long residue = lvalue % pow10;325lvalue /= pow10;326decExponent += i;327if ( residue >= (pow10>>1) ){328// round up based on the low-order bits we're discarding329lvalue++;330}331}332if ( lvalue <= Integer.MAX_VALUE ){333assert lvalue > 0L : lvalue; // lvalue <= 0334// even easier subcase!335// can do int arithmetic rather than long!336int ivalue = (int)lvalue;337ndigits = 10;338digits = perThreadBuffer.get();339digitno = ndigits-1;340c = ivalue%10;341ivalue /= 10;342while ( c == 0 ){343decExponent++;344c = ivalue%10;345ivalue /= 10;346}347while ( ivalue != 0){348digits[digitno--] = (char)(c+'0');349decExponent++;350c = ivalue%10;351ivalue /= 10;352}353digits[digitno] = (char)(c+'0');354} else {355// same algorithm as above (same bugs, too )356// but using long arithmetic.357ndigits = 20;358digits = perThreadBuffer.get();359digitno = ndigits-1;360c = (int)(lvalue%10L);361lvalue /= 10L;362while ( c == 0 ){363decExponent++;364c = (int)(lvalue%10L);365lvalue /= 10L;366}367while ( lvalue != 0L ){368digits[digitno--] = (char)(c+'0');369decExponent++;370c = (int)(lvalue%10L);371lvalue /= 10;372}373digits[digitno] = (char)(c+'0');374}375char result [];376ndigits -= digitno;377result = new char[ ndigits ];378System.arraycopy( digits, digitno, result, 0, ndigits );379this.digits = result;380this.decExponent = decExponent+1;381this.nDigits = ndigits;382}383384//385// add one to the least significant digit.386// in the unlikely event there is a carry out,387// deal with it.388// assert that this will only happen where there389// is only one digit, e.g. (float)1e-44 seems to do it.390//391private void392roundup(){393int i;394int q = digits[ i = (nDigits-1)];395if ( q == '9' ){396while ( q == '9' && i > 0 ){397digits[i] = '0';398q = digits[--i];399}400if ( q == '9' ){401// carryout! High-order 1, rest 0s, larger exp.402decExponent += 1;403digits[0] = '1';404return;405}406// else fall through.407}408digits[i] = (char)(q+1);409decimalDigitsRoundedUp = true;410}411412public boolean digitsRoundedUp() {413return decimalDigitsRoundedUp;414}415416/*417* FIRST IMPORTANT CONSTRUCTOR: DOUBLE418*/419public OldFloatingDecimalForTest( double d )420{421long dBits = Double.doubleToLongBits( d );422long fractBits;423int binExp;424int nSignificantBits;425426// discover and delete sign427if ( (dBits&signMask) != 0 ){428isNegative = true;429dBits ^= signMask;430} else {431isNegative = false;432}433// Begin to unpack434// Discover obvious special cases of NaN and Infinity.435binExp = (int)( (dBits&expMask) >> expShift );436fractBits = dBits&fractMask;437if ( binExp == (int)(expMask>>expShift) ) {438isExceptional = true;439if ( fractBits == 0L ){440digits = infinity;441} else {442digits = notANumber;443isNegative = false; // NaN has no sign!444}445nDigits = digits.length;446return;447}448isExceptional = false;449// Finish unpacking450// Normalize denormalized numbers.451// Insert assumed high-order bit for normalized numbers.452// Subtract exponent bias.453if ( binExp == 0 ){454if ( fractBits == 0L ){455// not a denorm, just a 0!456decExponent = 0;457digits = zero;458nDigits = 1;459return;460}461while ( (fractBits&fractHOB) == 0L ){462fractBits <<= 1;463binExp -= 1;464}465nSignificantBits = expShift + binExp +1; // recall binExp is - shift count.466binExp += 1;467} else {468fractBits |= fractHOB;469nSignificantBits = expShift+1;470}471binExp -= expBias;472// call the routine that actually does all the hard work.473dtoa( binExp, fractBits, nSignificantBits );474}475476/*477* SECOND IMPORTANT CONSTRUCTOR: SINGLE478*/479public OldFloatingDecimalForTest( float f )480{481int fBits = Float.floatToIntBits( f );482int fractBits;483int binExp;484int nSignificantBits;485486// discover and delete sign487if ( (fBits&singleSignMask) != 0 ){488isNegative = true;489fBits ^= singleSignMask;490} else {491isNegative = false;492}493// Begin to unpack494// Discover obvious special cases of NaN and Infinity.495binExp = (fBits&singleExpMask) >> singleExpShift;496fractBits = fBits&singleFractMask;497if ( binExp == (singleExpMask>>singleExpShift) ) {498isExceptional = true;499if ( fractBits == 0L ){500digits = infinity;501} else {502digits = notANumber;503isNegative = false; // NaN has no sign!504}505nDigits = digits.length;506return;507}508isExceptional = false;509// Finish unpacking510// Normalize denormalized numbers.511// Insert assumed high-order bit for normalized numbers.512// Subtract exponent bias.513if ( binExp == 0 ){514if ( fractBits == 0 ){515// not a denorm, just a 0!516decExponent = 0;517digits = zero;518nDigits = 1;519return;520}521while ( (fractBits&singleFractHOB) == 0 ){522fractBits <<= 1;523binExp -= 1;524}525nSignificantBits = singleExpShift + binExp +1; // recall binExp is - shift count.526binExp += 1;527} else {528fractBits |= singleFractHOB;529nSignificantBits = singleExpShift+1;530}531binExp -= singleExpBias;532// call the routine that actually does all the hard work.533dtoa( binExp, ((long)fractBits)<<(expShift-singleExpShift), nSignificantBits );534}535536private void537dtoa( int binExp, long fractBits, int nSignificantBits )538{539int nFractBits; // number of significant bits of fractBits;540int nTinyBits; // number of these to the right of the point.541int decExp;542543// Examine number. Determine if it is an easy case,544// which we can do pretty trivially using float/long conversion,545// or whether we must do real work.546nFractBits = countBits( fractBits );547nTinyBits = Math.max( 0, nFractBits - binExp - 1 );548if ( binExp <= maxSmallBinExp && binExp >= minSmallBinExp ){549// Look more closely at the number to decide if,550// with scaling by 10^nTinyBits, the result will fit in551// a long.552if ( (nTinyBits < long5pow.length) && ((nFractBits + n5bits[nTinyBits]) < 64 ) ){553/*554* We can do this:555* take the fraction bits, which are normalized.556* (a) nTinyBits == 0: Shift left or right appropriately557* to align the binary point at the extreme right, i.e.558* where a long int point is expected to be. The integer559* result is easily converted to a string.560* (b) nTinyBits > 0: Shift right by expShift-nFractBits,561* which effectively converts to long and scales by562* 2^nTinyBits. Then multiply by 5^nTinyBits to563* complete the scaling. We know this won't overflow564* because we just counted the number of bits necessary565* in the result. The integer you get from this can566* then be converted to a string pretty easily.567*/568long halfULP;569if ( nTinyBits == 0 ) {570if ( binExp > nSignificantBits ){571halfULP = 1L << ( binExp-nSignificantBits-1);572} else {573halfULP = 0L;574}575if ( binExp >= expShift ){576fractBits <<= (binExp-expShift);577} else {578fractBits >>>= (expShift-binExp) ;579}580developLongDigits( 0, fractBits, halfULP );581return;582}583/*584* The following causes excess digits to be printed585* out in the single-float case. Our manipulation of586* halfULP here is apparently not correct. If we587* better understand how this works, perhaps we can588* use this special case again. But for the time being,589* we do not.590* else {591* fractBits >>>= expShift+1-nFractBits;592* fractBits *= long5pow[ nTinyBits ];593* halfULP = long5pow[ nTinyBits ] >> (1+nSignificantBits-nFractBits);594* developLongDigits( -nTinyBits, fractBits, halfULP );595* return;596* }597*/598}599}600/*601* This is the hard case. We are going to compute large positive602* integers B and S and integer decExp, s.t.603* d = ( B / S ) * 10^decExp604* 1 <= B / S < 10605* Obvious choices are:606* decExp = floor( log10(d) )607* B = d * 2^nTinyBits * 10^max( 0, -decExp )608* S = 10^max( 0, decExp) * 2^nTinyBits609* (noting that nTinyBits has already been forced to non-negative)610* I am also going to compute a large positive integer611* M = (1/2^nSignificantBits) * 2^nTinyBits * 10^max( 0, -decExp )612* i.e. M is (1/2) of the ULP of d, scaled like B.613* When we iterate through dividing B/S and picking off the614* quotient bits, we will know when to stop when the remainder615* is <= M.616*617* We keep track of powers of 2 and powers of 5.618*/619620/*621* Estimate decimal exponent. (If it is small-ish,622* we could double-check.)623*624* First, scale the mantissa bits such that 1 <= d2 < 2.625* We are then going to estimate626* log10(d2) ~=~ (d2-1.5)/1.5 + log(1.5)627* and so we can estimate628* log10(d) ~=~ log10(d2) + binExp * log10(2)629* take the floor and call it decExp.630* FIXME -- use more precise constants here. It costs no more.631*/632double d2 = Double.longBitsToDouble(633expOne | ( fractBits &~ fractHOB ) );634decExp = (int)Math.floor(635(d2-1.5D)*0.289529654D + 0.176091259 + (double)binExp * 0.301029995663981 );636int B2, B5; // powers of 2 and powers of 5, respectively, in B637int S2, S5; // powers of 2 and powers of 5, respectively, in S638int M2, M5; // powers of 2 and powers of 5, respectively, in M639int Bbits; // binary digits needed to represent B, approx.640int tenSbits; // binary digits needed to represent 10*S, approx.641OldFDBigIntForTest Sval, Bval, Mval;642643B5 = Math.max( 0, -decExp );644B2 = B5 + nTinyBits + binExp;645646S5 = Math.max( 0, decExp );647S2 = S5 + nTinyBits;648649M5 = B5;650M2 = B2 - nSignificantBits;651652/*653* the long integer fractBits contains the (nFractBits) interesting654* bits from the mantissa of d ( hidden 1 added if necessary) followed655* by (expShift+1-nFractBits) zeros. In the interest of compactness,656* I will shift out those zeros before turning fractBits into a657* OldFDBigIntForTest. The resulting whole number will be658* d * 2^(nFractBits-1-binExp).659*/660fractBits >>>= (expShift+1-nFractBits);661B2 -= nFractBits-1;662int common2factor = Math.min( B2, S2 );663B2 -= common2factor;664S2 -= common2factor;665M2 -= common2factor;666667/*668* HACK!! For exact powers of two, the next smallest number669* is only half as far away as we think (because the meaning of670* ULP changes at power-of-two bounds) for this reason, we671* hack M2. Hope this works.672*/673if ( nFractBits == 1 )674M2 -= 1;675676if ( M2 < 0 ){677// oops.678// since we cannot scale M down far enough,679// we must scale the other values up.680B2 -= M2;681S2 -= M2;682M2 = 0;683}684/*685* Construct, Scale, iterate.686* Some day, we'll write a stopping test that takes687* account of the asymmetry of the spacing of floating-point688* numbers below perfect powers of 2689* 26 Sept 96 is not that day.690* So we use a symmetric test.691*/692char digits[] = this.digits = new char[18];693int ndigit = 0;694boolean low, high;695long lowDigitDifference;696int q;697698/*699* Detect the special cases where all the numbers we are about700* to compute will fit in int or long integers.701* In these cases, we will avoid doing OldFDBigIntForTest arithmetic.702* We use the same algorithms, except that we "normalize"703* our OldFDBigIntForTests before iterating. This is to make division easier,704* as it makes our fist guess (quotient of high-order words)705* more accurate!706*707* Some day, we'll write a stopping test that takes708* account of the asymmetry of the spacing of floating-point709* numbers below perfect powers of 2710* 26 Sept 96 is not that day.711* So we use a symmetric test.712*/713Bbits = nFractBits + B2 + (( B5 < n5bits.length )? n5bits[B5] : ( B5*3 ));714tenSbits = S2+1 + (( (S5+1) < n5bits.length )? n5bits[(S5+1)] : ( (S5+1)*3 ));715if ( Bbits < 64 && tenSbits < 64){716if ( Bbits < 32 && tenSbits < 32){717// wa-hoo! They're all ints!718int b = ((int)fractBits * small5pow[B5] ) << B2;719int s = small5pow[S5] << S2;720int m = small5pow[M5] << M2;721int tens = s * 10;722/*723* Unroll the first iteration. If our decExp estimate724* was too high, our first quotient will be zero. In this725* case, we discard it and decrement decExp.726*/727ndigit = 0;728q = b / s;729b = 10 * ( b % s );730m *= 10;731low = (b < m );732high = (b+m > tens );733assert q < 10 : q; // excessively large digit734if ( (q == 0) && ! high ){735// oops. Usually ignore leading zero.736decExp--;737} else {738digits[ndigit++] = (char)('0' + q);739}740/*741* HACK! Java spec sez that we always have at least742* one digit after the . in either F- or E-form output.743* Thus we will need more than one digit if we're using744* E-form745*/746if ( decExp < -3 || decExp >= 8 ){747high = low = false;748}749while( ! low && ! high ){750q = b / s;751b = 10 * ( b % s );752m *= 10;753assert q < 10 : q; // excessively large digit754if ( m > 0L ){755low = (b < m );756high = (b+m > tens );757} else {758// hack -- m might overflow!759// in this case, it is certainly > b,760// which won't761// and b+m > tens, too, since that has overflowed762// either!763low = true;764high = true;765}766digits[ndigit++] = (char)('0' + q);767}768lowDigitDifference = (b<<1) - tens;769exactDecimalConversion = (b == 0);770} else {771// still good! they're all longs!772long b = (fractBits * long5pow[B5] ) << B2;773long s = long5pow[S5] << S2;774long m = long5pow[M5] << M2;775long tens = s * 10L;776/*777* Unroll the first iteration. If our decExp estimate778* was too high, our first quotient will be zero. In this779* case, we discard it and decrement decExp.780*/781ndigit = 0;782q = (int) ( b / s );783b = 10L * ( b % s );784m *= 10L;785low = (b < m );786high = (b+m > tens );787assert q < 10 : q; // excessively large digit788if ( (q == 0) && ! high ){789// oops. Usually ignore leading zero.790decExp--;791} else {792digits[ndigit++] = (char)('0' + q);793}794/*795* HACK! Java spec sez that we always have at least796* one digit after the . in either F- or E-form output.797* Thus we will need more than one digit if we're using798* E-form799*/800if ( decExp < -3 || decExp >= 8 ){801high = low = false;802}803while( ! low && ! high ){804q = (int) ( b / s );805b = 10 * ( b % s );806m *= 10;807assert q < 10 : q; // excessively large digit808if ( m > 0L ){809low = (b < m );810high = (b+m > tens );811} else {812// hack -- m might overflow!813// in this case, it is certainly > b,814// which won't815// and b+m > tens, too, since that has overflowed816// either!817low = true;818high = true;819}820digits[ndigit++] = (char)('0' + q);821}822lowDigitDifference = (b<<1) - tens;823exactDecimalConversion = (b == 0);824}825} else {826OldFDBigIntForTest ZeroVal = new OldFDBigIntForTest(0);827OldFDBigIntForTest tenSval;828int shiftBias;829830/*831* We really must do OldFDBigIntForTest arithmetic.832* Fist, construct our OldFDBigIntForTest initial values.833*/834Bval = multPow52( new OldFDBigIntForTest( fractBits ), B5, B2 );835Sval = constructPow52( S5, S2 );836Mval = constructPow52( M5, M2 );837838839// normalize so that division works better840Bval.lshiftMe( shiftBias = Sval.normalizeMe() );841Mval.lshiftMe( shiftBias );842tenSval = Sval.mult( 10 );843/*844* Unroll the first iteration. If our decExp estimate845* was too high, our first quotient will be zero. In this846* case, we discard it and decrement decExp.847*/848ndigit = 0;849q = Bval.quoRemIteration( Sval );850Mval = Mval.mult( 10 );851low = (Bval.cmp( Mval ) < 0);852high = (Bval.add( Mval ).cmp( tenSval ) > 0 );853assert q < 10 : q; // excessively large digit854if ( (q == 0) && ! high ){855// oops. Usually ignore leading zero.856decExp--;857} else {858digits[ndigit++] = (char)('0' + q);859}860/*861* HACK! Java spec sez that we always have at least862* one digit after the . in either F- or E-form output.863* Thus we will need more than one digit if we're using864* E-form865*/866if ( decExp < -3 || decExp >= 8 ){867high = low = false;868}869while( ! low && ! high ){870q = Bval.quoRemIteration( Sval );871Mval = Mval.mult( 10 );872assert q < 10 : q; // excessively large digit873low = (Bval.cmp( Mval ) < 0);874high = (Bval.add( Mval ).cmp( tenSval ) > 0 );875digits[ndigit++] = (char)('0' + q);876}877if ( high && low ){878Bval.lshiftMe(1);879lowDigitDifference = Bval.cmp(tenSval);880} else {881lowDigitDifference = 0L; // this here only for flow analysis!882}883exactDecimalConversion = (Bval.cmp( ZeroVal ) == 0);884}885this.decExponent = decExp+1;886this.digits = digits;887this.nDigits = ndigit;888/*889* Last digit gets rounded based on stopping condition.890*/891if ( high ){892if ( low ){893if ( lowDigitDifference == 0L ){894// it's a tie!895// choose based on which digits we like.896if ( (digits[nDigits-1]&1) != 0 ) roundup();897} else if ( lowDigitDifference > 0 ){898roundup();899}900} else {901roundup();902}903}904}905906public boolean decimalDigitsExact() {907return exactDecimalConversion;908}909910public String911toString(){912// most brain-dead version913StringBuffer result = new StringBuffer( nDigits+8 );914if ( isNegative ){ result.append( '-' ); }915if ( isExceptional ){916result.append( digits, 0, nDigits );917} else {918result.append( "0.");919result.append( digits, 0, nDigits );920result.append('e');921result.append( decExponent );922}923return new String(result);924}925926public String toJavaFormatString() {927char result[] = perThreadBuffer.get();928int i = getChars(result);929return new String(result, 0, i);930}931932private int getChars(char[] result) {933assert nDigits <= 19 : nDigits; // generous bound on size of nDigits934int i = 0;935if (isNegative) { result[0] = '-'; i = 1; }936if (isExceptional) {937System.arraycopy(digits, 0, result, i, nDigits);938i += nDigits;939} else {940if (decExponent > 0 && decExponent < 8) {941// print digits.digits.942int charLength = Math.min(nDigits, decExponent);943System.arraycopy(digits, 0, result, i, charLength);944i += charLength;945if (charLength < decExponent) {946charLength = decExponent-charLength;947System.arraycopy(zero, 0, result, i, charLength);948i += charLength;949result[i++] = '.';950result[i++] = '0';951} else {952result[i++] = '.';953if (charLength < nDigits) {954int t = nDigits - charLength;955System.arraycopy(digits, charLength, result, i, t);956i += t;957} else {958result[i++] = '0';959}960}961} else if (decExponent <=0 && decExponent > -3) {962result[i++] = '0';963result[i++] = '.';964if (decExponent != 0) {965System.arraycopy(zero, 0, result, i, -decExponent);966i -= decExponent;967}968System.arraycopy(digits, 0, result, i, nDigits);969i += nDigits;970} else {971result[i++] = digits[0];972result[i++] = '.';973if (nDigits > 1) {974System.arraycopy(digits, 1, result, i, nDigits-1);975i += nDigits-1;976} else {977result[i++] = '0';978}979result[i++] = 'E';980int e;981if (decExponent <= 0) {982result[i++] = '-';983e = -decExponent+1;984} else {985e = decExponent-1;986}987// decExponent has 1, 2, or 3, digits988if (e <= 9) {989result[i++] = (char)(e+'0');990} else if (e <= 99) {991result[i++] = (char)(e/10 +'0');992result[i++] = (char)(e%10 + '0');993} else {994result[i++] = (char)(e/100+'0');995e %= 100;996result[i++] = (char)(e/10+'0');997result[i++] = (char)(e%10 + '0');998}999}1000}1001return i;1002}10031004// Per-thread buffer for string/stringbuffer conversion1005private static ThreadLocal<char[]> perThreadBuffer = new ThreadLocal<char[]>() {1006protected synchronized char[] initialValue() {1007return new char[26];1008}1009};10101011public void appendTo(Appendable buf) {1012char result[] = perThreadBuffer.get();1013int i = getChars(result);1014if (buf instanceof StringBuilder)1015((StringBuilder) buf).append(result, 0, i);1016else if (buf instanceof StringBuffer)1017((StringBuffer) buf).append(result, 0, i);1018else1019assert false;1020}10211022@SuppressWarnings("fallthrough")1023public static OldFloatingDecimalForTest1024readJavaFormatString( String in ) throws NumberFormatException {1025boolean isNegative = false;1026boolean signSeen = false;1027int decExp;1028char c;10291030parseNumber:1031try{1032in = in.trim(); // don't fool around with white space.1033// throws NullPointerException if null1034int l = in.length();1035if ( l == 0 ) throw new NumberFormatException("empty String");1036int i = 0;1037switch ( c = in.charAt( i ) ){1038case '-':1039isNegative = true;1040//FALLTHROUGH1041case '+':1042i++;1043signSeen = true;1044}10451046// Check for NaN and Infinity strings1047c = in.charAt(i);1048if(c == 'N' || c == 'I') { // possible NaN or infinity1049boolean potentialNaN = false;1050char targetChars[] = null; // char array of "NaN" or "Infinity"10511052if(c == 'N') {1053targetChars = notANumber;1054potentialNaN = true;1055} else {1056targetChars = infinity;1057}10581059// compare Input string to "NaN" or "Infinity"1060int j = 0;1061while(i < l && j < targetChars.length) {1062if(in.charAt(i) == targetChars[j]) {1063i++; j++;1064}1065else // something is amiss, throw exception1066break parseNumber;1067}10681069// For the candidate string to be a NaN or infinity,1070// all characters in input string and target char[]1071// must be matched ==> j must equal targetChars.length1072// and i must equal l1073if( (j == targetChars.length) && (i == l) ) { // return NaN or infinity1074return (potentialNaN ? new OldFloatingDecimalForTest(Double.NaN) // NaN has no sign1075: new OldFloatingDecimalForTest(isNegative?1076Double.NEGATIVE_INFINITY:1077Double.POSITIVE_INFINITY)) ;1078}1079else { // something went wrong, throw exception1080break parseNumber;1081}10821083} else if (c == '0') { // check for hexadecimal floating-point number1084if (l > i+1 ) {1085char ch = in.charAt(i+1);1086if (ch == 'x' || ch == 'X' ) // possible hex string1087return parseHexString(in);1088}1089} // look for and process decimal floating-point string10901091char[] digits = new char[ l ];1092int nDigits= 0;1093boolean decSeen = false;1094int decPt = 0;1095int nLeadZero = 0;1096int nTrailZero= 0;1097digitLoop:1098while ( i < l ){1099switch ( c = in.charAt( i ) ){1100case '0':1101if ( nDigits > 0 ){1102nTrailZero += 1;1103} else {1104nLeadZero += 1;1105}1106break; // out of switch.1107case '1':1108case '2':1109case '3':1110case '4':1111case '5':1112case '6':1113case '7':1114case '8':1115case '9':1116while ( nTrailZero > 0 ){1117digits[nDigits++] = '0';1118nTrailZero -= 1;1119}1120digits[nDigits++] = c;1121break; // out of switch.1122case '.':1123if ( decSeen ){1124// already saw one ., this is the 2nd.1125throw new NumberFormatException("multiple points");1126}1127decPt = i;1128if ( signSeen ){1129decPt -= 1;1130}1131decSeen = true;1132break; // out of switch.1133default:1134break digitLoop;1135}1136i++;1137}1138/*1139* At this point, we've scanned all the digits and decimal1140* point we're going to see. Trim off leading and trailing1141* zeros, which will just confuse us later, and adjust1142* our initial decimal exponent accordingly.1143* To review:1144* we have seen i total characters.1145* nLeadZero of them were zeros before any other digits.1146* nTrailZero of them were zeros after any other digits.1147* if ( decSeen ), then a . was seen after decPt characters1148* ( including leading zeros which have been discarded )1149* nDigits characters were neither lead nor trailing1150* zeros, nor point1151*/1152/*1153* special hack: if we saw no non-zero digits, then the1154* answer is zero!1155* Unfortunately, we feel honor-bound to keep parsing!1156*/1157if ( nDigits == 0 ){1158digits = zero;1159nDigits = 1;1160if ( nLeadZero == 0 ){1161// we saw NO DIGITS AT ALL,1162// not even a crummy 0!1163// this is not allowed.1164break parseNumber; // go throw exception1165}11661167}11681169/* Our initial exponent is decPt, adjusted by the number of1170* discarded zeros. Or, if there was no decPt,1171* then its just nDigits adjusted by discarded trailing zeros.1172*/1173if ( decSeen ){1174decExp = decPt - nLeadZero;1175} else {1176decExp = nDigits+nTrailZero;1177}11781179/*1180* Look for 'e' or 'E' and an optionally signed integer.1181*/1182if ( (i < l) && (((c = in.charAt(i) )=='e') || (c == 'E') ) ){1183int expSign = 1;1184int expVal = 0;1185int reallyBig = Integer.MAX_VALUE / 10;1186boolean expOverflow = false;1187switch( in.charAt(++i) ){1188case '-':1189expSign = -1;1190//FALLTHROUGH1191case '+':1192i++;1193}1194int expAt = i;1195expLoop:1196while ( i < l ){1197if ( expVal >= reallyBig ){1198// the next character will cause integer1199// overflow.1200expOverflow = true;1201}1202switch ( c = in.charAt(i++) ){1203case '0':1204case '1':1205case '2':1206case '3':1207case '4':1208case '5':1209case '6':1210case '7':1211case '8':1212case '9':1213expVal = expVal*10 + ( (int)c - (int)'0' );1214continue;1215default:1216i--; // back up.1217break expLoop; // stop parsing exponent.1218}1219}1220int expLimit = bigDecimalExponent+nDigits+nTrailZero;1221if ( expOverflow || ( expVal > expLimit ) ){1222//1223// The intent here is to end up with1224// infinity or zero, as appropriate.1225// The reason for yielding such a small decExponent,1226// rather than something intuitive such as1227// expSign*Integer.MAX_VALUE, is that this value1228// is subject to further manipulation in1229// doubleValue() and floatValue(), and I don't want1230// it to be able to cause overflow there!1231// (The only way we can get into trouble here is for1232// really outrageous nDigits+nTrailZero, such as 2 billion. )1233//1234decExp = expSign*expLimit;1235} else {1236// this should not overflow, since we tested1237// for expVal > (MAX+N), where N >= abs(decExp)1238decExp = decExp + expSign*expVal;1239}12401241// if we saw something not a digit ( or end of string )1242// after the [Ee][+-], without seeing any digits at all1243// this is certainly an error. If we saw some digits,1244// but then some trailing garbage, that might be ok.1245// so we just fall through in that case.1246// HUMBUG1247if ( i == expAt )1248break parseNumber; // certainly bad1249}1250/*1251* We parsed everything we could.1252* If there are leftovers, then this is not good input!1253*/1254if ( i < l &&1255((i != l - 1) ||1256(in.charAt(i) != 'f' &&1257in.charAt(i) != 'F' &&1258in.charAt(i) != 'd' &&1259in.charAt(i) != 'D'))) {1260break parseNumber; // go throw exception1261}12621263return new OldFloatingDecimalForTest( isNegative, decExp, digits, nDigits, false );1264} catch ( StringIndexOutOfBoundsException e ){ }1265throw new NumberFormatException("For input string: \"" + in + "\"");1266}12671268/*1269* Take a FloatingDecimal, which we presumably just scanned in,1270* and find out what its value is, as a double.1271*1272* AS A SIDE EFFECT, SET roundDir TO INDICATE PREFERRED1273* ROUNDING DIRECTION in case the result is really destined1274* for a single-precision float.1275*/12761277public strictfp double doubleValue(){1278int kDigits = Math.min( nDigits, maxDecimalDigits+1 );1279long lValue;1280double dValue;1281double rValue, tValue;12821283// First, check for NaN and Infinity values1284if(digits == infinity || digits == notANumber) {1285if(digits == notANumber)1286return Double.NaN;1287else1288return (isNegative?Double.NEGATIVE_INFINITY:Double.POSITIVE_INFINITY);1289}1290else {1291if (mustSetRoundDir) {1292roundDir = 0;1293}1294/*1295* convert the lead kDigits to a long integer.1296*/1297// (special performance hack: start to do it using int)1298int iValue = (int)digits[0]-(int)'0';1299int iDigits = Math.min( kDigits, intDecimalDigits );1300for ( int i=1; i < iDigits; i++ ){1301iValue = iValue*10 + (int)digits[i]-(int)'0';1302}1303lValue = (long)iValue;1304for ( int i=iDigits; i < kDigits; i++ ){1305lValue = lValue*10L + (long)((int)digits[i]-(int)'0');1306}1307dValue = (double)lValue;1308int exp = decExponent-kDigits;1309/*1310* lValue now contains a long integer with the value of1311* the first kDigits digits of the number.1312* dValue contains the (double) of the same.1313*/13141315if ( nDigits <= maxDecimalDigits ){1316/*1317* possibly an easy case.1318* We know that the digits can be represented1319* exactly. And if the exponent isn't too outrageous,1320* the whole thing can be done with one operation,1321* thus one rounding error.1322* Note that all our constructors trim all leading and1323* trailing zeros, so simple values (including zero)1324* will always end up here1325*/1326if (exp == 0 || dValue == 0.0)1327return (isNegative)? -dValue : dValue; // small floating integer1328else if ( exp >= 0 ){1329if ( exp <= maxSmallTen ){1330/*1331* Can get the answer with one operation,1332* thus one roundoff.1333*/1334rValue = dValue * small10pow[exp];1335if ( mustSetRoundDir ){1336tValue = rValue / small10pow[exp];1337roundDir = ( tValue == dValue ) ? 01338:( tValue < dValue ) ? 11339: -1;1340}1341return (isNegative)? -rValue : rValue;1342}1343int slop = maxDecimalDigits - kDigits;1344if ( exp <= maxSmallTen+slop ){1345/*1346* We can multiply dValue by 10^(slop)1347* and it is still "small" and exact.1348* Then we can multiply by 10^(exp-slop)1349* with one rounding.1350*/1351dValue *= small10pow[slop];1352rValue = dValue * small10pow[exp-slop];13531354if ( mustSetRoundDir ){1355tValue = rValue / small10pow[exp-slop];1356roundDir = ( tValue == dValue ) ? 01357:( tValue < dValue ) ? 11358: -1;1359}1360return (isNegative)? -rValue : rValue;1361}1362/*1363* Else we have a hard case with a positive exp.1364*/1365} else {1366if ( exp >= -maxSmallTen ){1367/*1368* Can get the answer in one division.1369*/1370rValue = dValue / small10pow[-exp];1371tValue = rValue * small10pow[-exp];1372if ( mustSetRoundDir ){1373roundDir = ( tValue == dValue ) ? 01374:( tValue < dValue ) ? 11375: -1;1376}1377return (isNegative)? -rValue : rValue;1378}1379/*1380* Else we have a hard case with a negative exp.1381*/1382}1383}13841385/*1386* Harder cases:1387* The sum of digits plus exponent is greater than1388* what we think we can do with one error.1389*1390* Start by approximating the right answer by,1391* naively, scaling by powers of 10.1392*/1393if ( exp > 0 ){1394if ( decExponent > maxDecimalExponent+1 ){1395/*1396* Lets face it. This is going to be1397* Infinity. Cut to the chase.1398*/1399return (isNegative)? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;1400}1401if ( (exp&15) != 0 ){1402dValue *= small10pow[exp&15];1403}1404if ( (exp>>=4) != 0 ){1405int j;1406for( j = 0; exp > 1; j++, exp>>=1 ){1407if ( (exp&1)!=0)1408dValue *= big10pow[j];1409}1410/*1411* The reason for the weird exp > 1 condition1412* in the above loop was so that the last multiply1413* would get unrolled. We handle it here.1414* It could overflow.1415*/1416double t = dValue * big10pow[j];1417if ( Double.isInfinite( t ) ){1418/*1419* It did overflow.1420* Look more closely at the result.1421* If the exponent is just one too large,1422* then use the maximum finite as our estimate1423* value. Else call the result infinity1424* and punt it.1425* ( I presume this could happen because1426* rounding forces the result here to be1427* an ULP or two larger than1428* Double.MAX_VALUE ).1429*/1430t = dValue / 2.0;1431t *= big10pow[j];1432if ( Double.isInfinite( t ) ){1433return (isNegative)? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;1434}1435t = Double.MAX_VALUE;1436}1437dValue = t;1438}1439} else if ( exp < 0 ){1440exp = -exp;1441if ( decExponent < minDecimalExponent-1 ){1442/*1443* Lets face it. This is going to be1444* zero. Cut to the chase.1445*/1446return (isNegative)? -0.0 : 0.0;1447}1448if ( (exp&15) != 0 ){1449dValue /= small10pow[exp&15];1450}1451if ( (exp>>=4) != 0 ){1452int j;1453for( j = 0; exp > 1; j++, exp>>=1 ){1454if ( (exp&1)!=0)1455dValue *= tiny10pow[j];1456}1457/*1458* The reason for the weird exp > 1 condition1459* in the above loop was so that the last multiply1460* would get unrolled. We handle it here.1461* It could underflow.1462*/1463double t = dValue * tiny10pow[j];1464if ( t == 0.0 ){1465/*1466* It did underflow.1467* Look more closely at the result.1468* If the exponent is just one too small,1469* then use the minimum finite as our estimate1470* value. Else call the result 0.01471* and punt it.1472* ( I presume this could happen because1473* rounding forces the result here to be1474* an ULP or two less than1475* Double.MIN_VALUE ).1476*/1477t = dValue * 2.0;1478t *= tiny10pow[j];1479if ( t == 0.0 ){1480return (isNegative)? -0.0 : 0.0;1481}1482t = Double.MIN_VALUE;1483}1484dValue = t;1485}1486}14871488/*1489* dValue is now approximately the result.1490* The hard part is adjusting it, by comparison1491* with OldFDBigIntForTest arithmetic.1492* Formulate the EXACT big-number result as1493* bigD0 * 10^exp1494*/1495OldFDBigIntForTest bigD0 = new OldFDBigIntForTest( lValue, digits, kDigits, nDigits );1496exp = decExponent - nDigits;14971498correctionLoop:1499while(true){1500/* AS A SIDE EFFECT, THIS METHOD WILL SET THE INSTANCE VARIABLES1501* bigIntExp and bigIntNBits1502*/1503OldFDBigIntForTest bigB = doubleToBigInt( dValue );15041505/*1506* Scale bigD, bigB appropriately for1507* big-integer operations.1508* Naively, we multiply by powers of ten1509* and powers of two. What we actually do1510* is keep track of the powers of 5 and1511* powers of 2 we would use, then factor out1512* common divisors before doing the work.1513*/1514int B2, B5; // powers of 2, 5 in bigB1515int D2, D5; // powers of 2, 5 in bigD1516int Ulp2; // powers of 2 in halfUlp.1517if ( exp >= 0 ){1518B2 = B5 = 0;1519D2 = D5 = exp;1520} else {1521B2 = B5 = -exp;1522D2 = D5 = 0;1523}1524if ( bigIntExp >= 0 ){1525B2 += bigIntExp;1526} else {1527D2 -= bigIntExp;1528}1529Ulp2 = B2;1530// shift bigB and bigD left by a number s. t.1531// halfUlp is still an integer.1532int hulpbias;1533if ( bigIntExp+bigIntNBits <= -expBias+1 ){1534// This is going to be a denormalized number1535// (if not actually zero).1536// half an ULP is at 2^-(expBias+expShift+1)1537hulpbias = bigIntExp+ expBias + expShift;1538} else {1539hulpbias = expShift + 2 - bigIntNBits;1540}1541B2 += hulpbias;1542D2 += hulpbias;1543// if there are common factors of 2, we might just as well1544// factor them out, as they add nothing useful.1545int common2 = Math.min( B2, Math.min( D2, Ulp2 ) );1546B2 -= common2;1547D2 -= common2;1548Ulp2 -= common2;1549// do multiplications by powers of 5 and 21550bigB = multPow52( bigB, B5, B2 );1551OldFDBigIntForTest bigD = multPow52( new OldFDBigIntForTest( bigD0 ), D5, D2 );1552//1553// to recap:1554// bigB is the scaled-big-int version of our floating-point1555// candidate.1556// bigD is the scaled-big-int version of the exact value1557// as we understand it.1558// halfUlp is 1/2 an ulp of bigB, except for special cases1559// of exact powers of 21560//1561// the plan is to compare bigB with bigD, and if the difference1562// is less than halfUlp, then we're satisfied. Otherwise,1563// use the ratio of difference to halfUlp to calculate a fudge1564// factor to add to the floating value, then go 'round again.1565//1566OldFDBigIntForTest diff;1567int cmpResult;1568boolean overvalue;1569if ( (cmpResult = bigB.cmp( bigD ) ) > 0 ){1570overvalue = true; // our candidate is too big.1571diff = bigB.sub( bigD );1572if ( (bigIntNBits == 1) && (bigIntExp > -expBias+1) ){1573// candidate is a normalized exact power of 2 and1574// is too big. We will be subtracting.1575// For our purposes, ulp is the ulp of the1576// next smaller range.1577Ulp2 -= 1;1578if ( Ulp2 < 0 ){1579// rats. Cannot de-scale ulp this far.1580// must scale diff in other direction.1581Ulp2 = 0;1582diff.lshiftMe( 1 );1583}1584}1585} else if ( cmpResult < 0 ){1586overvalue = false; // our candidate is too small.1587diff = bigD.sub( bigB );1588} else {1589// the candidate is exactly right!1590// this happens with surprising frequency1591break correctionLoop;1592}1593OldFDBigIntForTest halfUlp = constructPow52( B5, Ulp2 );1594if ( (cmpResult = diff.cmp( halfUlp ) ) < 0 ){1595// difference is small.1596// this is close enough1597if (mustSetRoundDir) {1598roundDir = overvalue ? -1 : 1;1599}1600break correctionLoop;1601} else if ( cmpResult == 0 ){1602// difference is exactly half an ULP1603// round to some other value maybe, then finish1604dValue += 0.5*ulp( dValue, overvalue );1605// should check for bigIntNBits == 1 here??1606if (mustSetRoundDir) {1607roundDir = overvalue ? -1 : 1;1608}1609break correctionLoop;1610} else {1611// difference is non-trivial.1612// could scale addend by ratio of difference to1613// halfUlp here, if we bothered to compute that difference.1614// Most of the time ( I hope ) it is about 1 anyway.1615dValue += ulp( dValue, overvalue );1616if ( dValue == 0.0 || dValue == Double.POSITIVE_INFINITY )1617break correctionLoop; // oops. Fell off end of range.1618continue; // try again.1619}16201621}1622return (isNegative)? -dValue : dValue;1623}1624}16251626/*1627* Take a FloatingDecimal, which we presumably just scanned in,1628* and find out what its value is, as a float.1629* This is distinct from doubleValue() to avoid the extremely1630* unlikely case of a double rounding error, wherein the conversion1631* to double has one rounding error, and the conversion of that double1632* to a float has another rounding error, IN THE WRONG DIRECTION,1633* ( because of the preference to a zero low-order bit ).1634*/16351636public strictfp float floatValue(){1637int kDigits = Math.min( nDigits, singleMaxDecimalDigits+1 );1638int iValue;1639float fValue;16401641// First, check for NaN and Infinity values1642if(digits == infinity || digits == notANumber) {1643if(digits == notANumber)1644return Float.NaN;1645else1646return (isNegative?Float.NEGATIVE_INFINITY:Float.POSITIVE_INFINITY);1647}1648else {1649/*1650* convert the lead kDigits to an integer.1651*/1652iValue = (int)digits[0]-(int)'0';1653for ( int i=1; i < kDigits; i++ ){1654iValue = iValue*10 + (int)digits[i]-(int)'0';1655}1656fValue = (float)iValue;1657int exp = decExponent-kDigits;1658/*1659* iValue now contains an integer with the value of1660* the first kDigits digits of the number.1661* fValue contains the (float) of the same.1662*/16631664if ( nDigits <= singleMaxDecimalDigits ){1665/*1666* possibly an easy case.1667* We know that the digits can be represented1668* exactly. And if the exponent isn't too outrageous,1669* the whole thing can be done with one operation,1670* thus one rounding error.1671* Note that all our constructors trim all leading and1672* trailing zeros, so simple values (including zero)1673* will always end up here.1674*/1675if (exp == 0 || fValue == 0.0f)1676return (isNegative)? -fValue : fValue; // small floating integer1677else if ( exp >= 0 ){1678if ( exp <= singleMaxSmallTen ){1679/*1680* Can get the answer with one operation,1681* thus one roundoff.1682*/1683fValue *= singleSmall10pow[exp];1684return (isNegative)? -fValue : fValue;1685}1686int slop = singleMaxDecimalDigits - kDigits;1687if ( exp <= singleMaxSmallTen+slop ){1688/*1689* We can multiply dValue by 10^(slop)1690* and it is still "small" and exact.1691* Then we can multiply by 10^(exp-slop)1692* with one rounding.1693*/1694fValue *= singleSmall10pow[slop];1695fValue *= singleSmall10pow[exp-slop];1696return (isNegative)? -fValue : fValue;1697}1698/*1699* Else we have a hard case with a positive exp.1700*/1701} else {1702if ( exp >= -singleMaxSmallTen ){1703/*1704* Can get the answer in one division.1705*/1706fValue /= singleSmall10pow[-exp];1707return (isNegative)? -fValue : fValue;1708}1709/*1710* Else we have a hard case with a negative exp.1711*/1712}1713} else if ( (decExponent >= nDigits) && (nDigits+decExponent <= maxDecimalDigits) ){1714/*1715* In double-precision, this is an exact floating integer.1716* So we can compute to double, then shorten to float1717* with one round, and get the right answer.1718*1719* First, finish accumulating digits.1720* Then convert that integer to a double, multiply1721* by the appropriate power of ten, and convert to float.1722*/1723long lValue = (long)iValue;1724for ( int i=kDigits; i < nDigits; i++ ){1725lValue = lValue*10L + (long)((int)digits[i]-(int)'0');1726}1727double dValue = (double)lValue;1728exp = decExponent-nDigits;1729dValue *= small10pow[exp];1730fValue = (float)dValue;1731return (isNegative)? -fValue : fValue;17321733}1734/*1735* Harder cases:1736* The sum of digits plus exponent is greater than1737* what we think we can do with one error.1738*1739* Start by weeding out obviously out-of-range1740* results, then convert to double and go to1741* common hard-case code.1742*/1743if ( decExponent > singleMaxDecimalExponent+1 ){1744/*1745* Lets face it. This is going to be1746* Infinity. Cut to the chase.1747*/1748return (isNegative)? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;1749} else if ( decExponent < singleMinDecimalExponent-1 ){1750/*1751* Lets face it. This is going to be1752* zero. Cut to the chase.1753*/1754return (isNegative)? -0.0f : 0.0f;1755}17561757/*1758* Here, we do 'way too much work, but throwing away1759* our partial results, and going and doing the whole1760* thing as double, then throwing away half the bits that computes1761* when we convert back to float.1762*1763* The alternative is to reproduce the whole multiple-precision1764* algorithm for float precision, or to try to parameterize it1765* for common usage. The former will take about 400 lines of code,1766* and the latter I tried without success. Thus the semi-hack1767* answer here.1768*/1769mustSetRoundDir = !fromHex;1770double dValue = doubleValue();1771return stickyRound( dValue );1772}1773}177417751776/*1777* All the positive powers of 10 that can be1778* represented exactly in double/float.1779*/1780private static final double small10pow[] = {17811.0e0,17821.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5,17831.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10,17841.0e11, 1.0e12, 1.0e13, 1.0e14, 1.0e15,17851.0e16, 1.0e17, 1.0e18, 1.0e19, 1.0e20,17861.0e21, 1.0e221787};17881789private static final float singleSmall10pow[] = {17901.0e0f,17911.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,17921.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f1793};17941795private static final double big10pow[] = {17961e16, 1e32, 1e64, 1e128, 1e256 };1797private static final double tiny10pow[] = {17981e-16, 1e-32, 1e-64, 1e-128, 1e-256 };17991800private static final int maxSmallTen = small10pow.length-1;1801private static final int singleMaxSmallTen = singleSmall10pow.length-1;18021803private static final int small5pow[] = {18041,18055,18065*5,18075*5*5,18085*5*5*5,18095*5*5*5*5,18105*5*5*5*5*5,18115*5*5*5*5*5*5,18125*5*5*5*5*5*5*5,18135*5*5*5*5*5*5*5*5,18145*5*5*5*5*5*5*5*5*5,18155*5*5*5*5*5*5*5*5*5*5,18165*5*5*5*5*5*5*5*5*5*5*5,18175*5*5*5*5*5*5*5*5*5*5*5*51818};181918201821private static final long long5pow[] = {18221L,18235L,18245L*5,18255L*5*5,18265L*5*5*5,18275L*5*5*5*5,18285L*5*5*5*5*5,18295L*5*5*5*5*5*5,18305L*5*5*5*5*5*5*5,18315L*5*5*5*5*5*5*5*5,18325L*5*5*5*5*5*5*5*5*5,18335L*5*5*5*5*5*5*5*5*5*5,18345L*5*5*5*5*5*5*5*5*5*5*5,18355L*5*5*5*5*5*5*5*5*5*5*5*5,18365L*5*5*5*5*5*5*5*5*5*5*5*5*5,18375L*5*5*5*5*5*5*5*5*5*5*5*5*5*5,18385L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,18395L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,18405L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,18415L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,18425L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,18435L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,18445L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,18455L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,18465L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,18475L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,18485L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,1849};18501851// approximately ceil( log2( long5pow[i] ) )1852private static final int n5bits[] = {18530,18543,18555,18567,185710,185812,185914,186017,186119,186221,186324,186426,186528,186631,186733,186835,186938,187040,187142,187245,187347,187449,187552,187654,187756,187859,187961,1880};18811882private static final char infinity[] = { 'I', 'n', 'f', 'i', 'n', 'i', 't', 'y' };1883private static final char notANumber[] = { 'N', 'a', 'N' };1884private static final char zero[] = { '0', '0', '0', '0', '0', '0', '0', '0' };188518861887/*1888* Grammar is compatible with hexadecimal floating-point constants1889* described in section 6.4.4.2 of the C99 specification.1890*/1891private static Pattern hexFloatPattern = null;1892private static synchronized Pattern getHexFloatPattern() {1893if (hexFloatPattern == null) {1894hexFloatPattern = Pattern.compile(1895//1 234 56 7 8 91896"([-+])?0[xX](((\\p{XDigit}+)\\.?)|((\\p{XDigit}*)\\.(\\p{XDigit}+)))[pP]([-+])?(\\p{Digit}+)[fFdD]?"1897);1898}1899return hexFloatPattern;1900}19011902/*1903* Convert string s to a suitable floating decimal; uses the1904* double constructor and set the roundDir variable appropriately1905* in case the value is later converted to a float.1906*/1907static OldFloatingDecimalForTest parseHexString(String s) {1908// Verify string is a member of the hexadecimal floating-point1909// string language.1910Matcher m = getHexFloatPattern().matcher(s);1911boolean validInput = m.matches();19121913if (!validInput) {1914// Input does not match pattern1915throw new NumberFormatException("For input string: \"" + s + "\"");1916} else { // validInput1917/*1918* We must isolate the sign, significand, and exponent1919* fields. The sign value is straightforward. Since1920* floating-point numbers are stored with a normalized1921* representation, the significand and exponent are1922* interrelated.1923*1924* After extracting the sign, we normalized the1925* significand as a hexadecimal value, calculating an1926* exponent adjust for any shifts made during1927* normalization. If the significand is zero, the1928* exponent doesn't need to be examined since the output1929* will be zero.1930*1931* Next the exponent in the input string is extracted.1932* Afterwards, the significand is normalized as a *binary*1933* value and the input value's normalized exponent can be1934* computed. The significand bits are copied into a1935* double significand; if the string has more logical bits1936* than can fit in a double, the extra bits affect the1937* round and sticky bits which are used to round the final1938* value.1939*/19401941// Extract significand sign1942String group1 = m.group(1);1943double sign = (( group1 == null ) || group1.equals("+"))? 1.0 : -1.0;194419451946// Extract Significand magnitude1947/*1948* Based on the form of the significand, calculate how the1949* binary exponent needs to be adjusted to create a1950* normalized *hexadecimal* floating-point number; that1951* is, a number where there is one nonzero hex digit to1952* the left of the (hexa)decimal point. Since we are1953* adjusting a binary, not hexadecimal exponent, the1954* exponent is adjusted by a multiple of 4.1955*1956* There are a number of significand scenarios to consider;1957* letters are used in indicate nonzero digits:1958*1959* 1. 000xxxx => x.xxx normalized1960* increase exponent by (number of x's - 1)*41961*1962* 2. 000xxx.yyyy => x.xxyyyy normalized1963* increase exponent by (number of x's - 1)*41964*1965* 3. .000yyy => y.yy normalized1966* decrease exponent by (number of zeros + 1)*41967*1968* 4. 000.00000yyy => y.yy normalized1969* decrease exponent by (number of zeros to right of point + 1)*41970*1971* If the significand is exactly zero, return a properly1972* signed zero.1973*/19741975String significandString =null;1976int signifLength = 0;1977int exponentAdjust = 0;1978{1979int leftDigits = 0; // number of meaningful digits to1980// left of "decimal" point1981// (leading zeros stripped)1982int rightDigits = 0; // number of digits to right of1983// "decimal" point; leading zeros1984// must always be accounted for1985/*1986* The significand is made up of either1987*1988* 1. group 4 entirely (integer portion only)1989*1990* OR1991*1992* 2. the fractional portion from group 7 plus any1993* (optional) integer portions from group 6.1994*/1995String group4;1996if( (group4 = m.group(4)) != null) { // Integer-only significand1997// Leading zeros never matter on the integer portion1998significandString = stripLeadingZeros(group4);1999leftDigits = significandString.length();2000}2001else {2002// Group 6 is the optional integer; leading zeros2003// never matter on the integer portion2004String group6 = stripLeadingZeros(m.group(6));2005leftDigits = group6.length();20062007// fraction2008String group7 = m.group(7);2009rightDigits = group7.length();20102011// Turn "integer.fraction" into "integer"+"fraction"2012significandString =2013((group6 == null)?"":group6) + // is the null2014// check necessary?2015group7;2016}20172018significandString = stripLeadingZeros(significandString);2019signifLength = significandString.length();20202021/*2022* Adjust exponent as described above2023*/2024if (leftDigits >= 1) { // Cases 1 and 22025exponentAdjust = 4*(leftDigits - 1);2026} else { // Cases 3 and 42027exponentAdjust = -4*( rightDigits - signifLength + 1);2028}20292030// If the significand is zero, the exponent doesn't2031// matter; return a properly signed zero.20322033if (signifLength == 0) { // Only zeros in input2034return new OldFloatingDecimalForTest(sign * 0.0);2035}2036}20372038// Extract Exponent2039/*2040* Use an int to read in the exponent value; this should2041* provide more than sufficient range for non-contrived2042* inputs. If reading the exponent in as an int does2043* overflow, examine the sign of the exponent and2044* significand to determine what to do.2045*/2046String group8 = m.group(8);2047boolean positiveExponent = ( group8 == null ) || group8.equals("+");2048long unsignedRawExponent;2049try {2050unsignedRawExponent = Integer.parseInt(m.group(9));2051}2052catch (NumberFormatException e) {2053// At this point, we know the exponent is2054// syntactically well-formed as a sequence of2055// digits. Therefore, if an NumberFormatException2056// is thrown, it must be due to overflowing int's2057// range. Also, at this point, we have already2058// checked for a zero significand. Thus the signs2059// of the exponent and significand determine the2060// final result:2061//2062// significand2063// + -2064// exponent + +infinity -infinity2065// - +0.0 -0.02066return new OldFloatingDecimalForTest(sign * (positiveExponent ?2067Double.POSITIVE_INFINITY : 0.0));2068}20692070long rawExponent =2071(positiveExponent ? 1L : -1L) * // exponent sign2072unsignedRawExponent; // exponent magnitude20732074// Calculate partially adjusted exponent2075long exponent = rawExponent + exponentAdjust ;20762077// Starting copying non-zero bits into proper position in2078// a long; copy explicit bit too; this will be masked2079// later for normal values.20802081boolean round = false;2082boolean sticky = false;2083int bitsCopied=0;2084int nextShift=0;2085long significand=0L;2086// First iteration is different, since we only copy2087// from the leading significand bit; one more exponent2088// adjust will be needed...20892090// IMPORTANT: make leadingDigit a long to avoid2091// surprising shift semantics!2092long leadingDigit = getHexDigit(significandString, 0);20932094/*2095* Left shift the leading digit (53 - (bit position of2096* leading 1 in digit)); this sets the top bit of the2097* significand to 1. The nextShift value is adjusted2098* to take into account the number of bit positions of2099* the leadingDigit actually used. Finally, the2100* exponent is adjusted to normalize the significand2101* as a binary value, not just a hex value.2102*/2103if (leadingDigit == 1) {2104significand |= leadingDigit << 52;2105nextShift = 52 - 4;2106/* exponent += 0 */ }2107else if (leadingDigit <= 3) { // [2, 3]2108significand |= leadingDigit << 51;2109nextShift = 52 - 5;2110exponent += 1;2111}2112else if (leadingDigit <= 7) { // [4, 7]2113significand |= leadingDigit << 50;2114nextShift = 52 - 6;2115exponent += 2;2116}2117else if (leadingDigit <= 15) { // [8, f]2118significand |= leadingDigit << 49;2119nextShift = 52 - 7;2120exponent += 3;2121} else {2122throw new AssertionError("Result from digit conversion too large!");2123}2124// The preceding if-else could be replaced by a single2125// code block based on the high-order bit set in2126// leadingDigit. Given leadingOnePosition,21272128// significand |= leadingDigit << (SIGNIFICAND_WIDTH - leadingOnePosition);2129// nextShift = 52 - (3 + leadingOnePosition);2130// exponent += (leadingOnePosition-1);213121322133/*2134* Now the exponent variable is equal to the normalized2135* binary exponent. Code below will make representation2136* adjustments if the exponent is incremented after2137* rounding (includes overflows to infinity) or if the2138* result is subnormal.2139*/21402141// Copy digit into significand until the significand can't2142// hold another full hex digit or there are no more input2143// hex digits.2144int i = 0;2145for(i = 1;2146i < signifLength && nextShift >= 0;2147i++) {2148long currentDigit = getHexDigit(significandString, i);2149significand |= (currentDigit << nextShift);2150nextShift-=4;2151}21522153// After the above loop, the bulk of the string is copied.2154// Now, we must copy any partial hex digits into the2155// significand AND compute the round bit and start computing2156// sticky bit.21572158if ( i < signifLength ) { // at least one hex input digit exists2159long currentDigit = getHexDigit(significandString, i);21602161// from nextShift, figure out how many bits need2162// to be copied, if any2163switch(nextShift) { // must be negative2164case -1:2165// three bits need to be copied in; can2166// set round bit2167significand |= ((currentDigit & 0xEL) >> 1);2168round = (currentDigit & 0x1L) != 0L;2169break;21702171case -2:2172// two bits need to be copied in; can2173// set round and start sticky2174significand |= ((currentDigit & 0xCL) >> 2);2175round = (currentDigit &0x2L) != 0L;2176sticky = (currentDigit & 0x1L) != 0;2177break;21782179case -3:2180// one bit needs to be copied in2181significand |= ((currentDigit & 0x8L)>>3);2182// Now set round and start sticky, if possible2183round = (currentDigit &0x4L) != 0L;2184sticky = (currentDigit & 0x3L) != 0;2185break;21862187case -4:2188// all bits copied into significand; set2189// round and start sticky2190round = ((currentDigit & 0x8L) != 0); // is top bit set?2191// nonzeros in three low order bits?2192sticky = (currentDigit & 0x7L) != 0;2193break;21942195default:2196throw new AssertionError("Unexpected shift distance remainder.");2197// break;2198}21992200// Round is set; sticky might be set.22012202// For the sticky bit, it suffices to check the2203// current digit and test for any nonzero digits in2204// the remaining unprocessed input.2205i++;2206while(i < signifLength && !sticky) {2207currentDigit = getHexDigit(significandString,i);2208sticky = sticky || (currentDigit != 0);2209i++;2210}22112212}2213// else all of string was seen, round and sticky are2214// correct as false.221522162217// Check for overflow and update exponent accordingly.22182219if (exponent > DoubleConsts.MAX_EXPONENT) { // Infinite result2220// overflow to properly signed infinity2221return new OldFloatingDecimalForTest(sign * Double.POSITIVE_INFINITY);2222} else { // Finite return value2223if (exponent <= DoubleConsts.MAX_EXPONENT && // (Usually) normal result2224exponent >= DoubleConsts.MIN_EXPONENT) {22252226// The result returned in this block cannot be a2227// zero or subnormal; however after the2228// significand is adjusted from rounding, we could2229// still overflow in infinity.22302231// AND exponent bits into significand; if the2232// significand is incremented and overflows from2233// rounding, this combination will update the2234// exponent correctly, even in the case of2235// Double.MAX_VALUE overflowing to infinity.22362237significand = (( (exponent +2238(long)DoubleConsts.EXP_BIAS) <<2239(DoubleConsts.SIGNIFICAND_WIDTH-1))2240& DoubleConsts.EXP_BIT_MASK) |2241(DoubleConsts.SIGNIF_BIT_MASK & significand);22422243} else { // Subnormal or zero2244// (exponent < DoubleConsts.MIN_EXPONENT)22452246if (exponent < (DoubleConsts.MIN_SUB_EXPONENT -1 )) {2247// No way to round back to nonzero value2248// regardless of significand if the exponent is2249// less than -1075.2250return new OldFloatingDecimalForTest(sign * 0.0);2251} else { // -1075 <= exponent <= MIN_EXPONENT -1 = -10232252/*2253* Find bit position to round to; recompute2254* round and sticky bits, and shift2255* significand right appropriately.2256*/22572258sticky = sticky || round;2259round = false;22602261// Number of bits of significand to preserve is2262// exponent - abs_min_exp +12263// check:2264// -1075 +1074 + 1 = 02265// -1023 +1074 + 1 = 5222662267int bitsDiscarded = 53 -2268((int)exponent - DoubleConsts.MIN_SUB_EXPONENT + 1);2269assert bitsDiscarded >= 1 && bitsDiscarded <= 53;22702271// What to do here:2272// First, isolate the new round bit2273round = (significand & (1L << (bitsDiscarded -1))) != 0L;2274if (bitsDiscarded > 1) {2275// create mask to update sticky bits; low2276// order bitsDiscarded bits should be 12277long mask = ~((~0L) << (bitsDiscarded -1));2278sticky = sticky || ((significand & mask) != 0L ) ;2279}22802281// Now, discard the bits2282significand = significand >> bitsDiscarded;22832284significand = (( ((long)(DoubleConsts.MIN_EXPONENT -1) + // subnorm exp.2285(long)DoubleConsts.EXP_BIAS) <<2286(DoubleConsts.SIGNIFICAND_WIDTH-1))2287& DoubleConsts.EXP_BIT_MASK) |2288(DoubleConsts.SIGNIF_BIT_MASK & significand);2289}2290}22912292// The significand variable now contains the currently2293// appropriate exponent bits too.22942295/*2296* Determine if significand should be incremented;2297* making this determination depends on the least2298* significant bit and the round and sticky bits.2299*2300* Round to nearest even rounding table, adapted from2301* table 4.7 in "Computer Arithmetic" by IsraelKoren.2302* The digit to the left of the "decimal" point is the2303* least significant bit, the digits to the right of2304* the point are the round and sticky bits2305*2306* Number Round(x)2307* x0.00 x0.2308* x0.01 x0.2309* x0.10 x0.2310* x0.11 x1. = x0. +12311* x1.00 x1.2312* x1.01 x1.2313* x1.10 x1. + 12314* x1.11 x1. + 12315*/2316boolean incremented = false;2317boolean leastZero = ((significand & 1L) == 0L);2318if( ( leastZero && round && sticky ) ||2319((!leastZero) && round )) {2320incremented = true;2321significand++;2322}23232324OldFloatingDecimalForTest fd = new OldFloatingDecimalForTest(Math.copySign(2325Double.longBitsToDouble(significand),2326sign));23272328/*2329* Set roundingDir variable field of fd properly so2330* that the input string can be properly rounded to a2331* float value. There are two cases to consider:2332*2333* 1. rounding to double discards sticky bit2334* information that would change the result of a float2335* rounding (near halfway case between two floats)2336*2337* 2. rounding to double rounds up when rounding up2338* would not occur when rounding to float.2339*2340* For former case only needs to be considered when2341* the bits rounded away when casting to float are all2342* zero; otherwise, float round bit is properly set2343* and sticky will already be true.2344*2345* The lower exponent bound for the code below is the2346* minimum (normalized) subnormal exponent - 1 since a2347* value with that exponent can round up to the2348* minimum subnormal value and the sticky bit2349* information must be preserved (i.e. case 1).2350*/2351if ((exponent >= FloatConsts.MIN_SUB_EXPONENT-1) &&2352(exponent <= FloatConsts.MAX_EXPONENT ) ){2353// Outside above exponent range, the float value2354// will be zero or infinity.23552356/*2357* If the low-order 28 bits of a rounded double2358* significand are 0, the double could be a2359* half-way case for a rounding to float. If the2360* double value is a half-way case, the double2361* significand may have to be modified to round2362* the the right float value (see the stickyRound2363* method). If the rounding to double has lost2364* what would be float sticky bit information, the2365* double significand must be incremented. If the2366* double value's significand was itself2367* incremented, the float value may end up too2368* large so the increment should be undone.2369*/2370if ((significand & 0xfffffffL) == 0x0L) {2371// For negative values, the sign of the2372// roundDir is the same as for positive values2373// since adding 1 increasing the significand's2374// magnitude and subtracting 1 decreases the2375// significand's magnitude. If neither round2376// nor sticky is true, the double value is2377// exact and no adjustment is required for a2378// proper float rounding.2379if( round || sticky) {2380if (leastZero) { // prerounding lsb is 02381// If round and sticky were both true,2382// and the least significant2383// significand bit were 0, the rounded2384// significand would not have its2385// low-order bits be zero. Therefore,2386// we only need to adjust the2387// significand if round XOR sticky is2388// true.2389if (round ^ sticky) {2390fd.roundDir = 1;2391}2392}2393else { // prerounding lsb is 12394// If the prerounding lsb is 1 and the2395// resulting significand has its2396// low-order bits zero, the significand2397// was incremented. Here, we undo the2398// increment, which will ensure the2399// right guard and sticky bits for the2400// float rounding.2401if (round)2402fd.roundDir = -1;2403}2404}2405}2406}24072408fd.fromHex = true;2409return fd;2410}2411}2412}24132414/**2415* Return <code>s</code> with any leading zeros removed.2416*/2417static String stripLeadingZeros(String s) {2418return s.replaceFirst("^0+", "");2419}24202421/**2422* Extract a hexadecimal digit from position <code>position</code>2423* of string <code>s</code>.2424*/2425static int getHexDigit(String s, int position) {2426int value = Character.digit(s.charAt(position), 16);2427if (value <= -1 || value >= 16) {2428throw new AssertionError("Unexpected failure of digit conversion of " +2429s.charAt(position));2430}2431return value;2432}243324342435}243624372438