1 /*
   2  * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.internal.math;
  27 
  28 import java.util.Arrays;
  29 import java.util.regex.*;
  30 
  31 /**
  32  * A class for converting between ASCII and decimal representations of a single
  33  * or double precision floating point number. Most conversions are provided via
  34  * static convenience methods, although a <code>BinaryToASCIIConverter</code>
  35  * instance may be obtained and reused.
  36  */
  37 public class FloatingDecimal{
  38     //
  39     // Constants of the implementation;
  40     // most are IEEE-754 related.
  41     // (There are more really boring constants at the end.)
  42     //
  43     static final int    EXP_SHIFT = DoubleConsts.SIGNIFICAND_WIDTH - 1;
  44     static final long   FRACT_HOB = ( 1L<<EXP_SHIFT ); // assumed High-Order bit
  45     static final long   EXP_ONE   = ((long)DoubleConsts.EXP_BIAS)<<EXP_SHIFT; // exponent of 1.0
  46     static final int    MAX_SMALL_BIN_EXP = 62;
  47     static final int    MIN_SMALL_BIN_EXP = -( 63 / 3 );
  48     static final int    MAX_DECIMAL_DIGITS = 15;
  49     static final int    MAX_DECIMAL_EXPONENT = 308;
  50     static final int    MIN_DECIMAL_EXPONENT = -324;
  51     static final int    BIG_DECIMAL_EXPONENT = 324; // i.e. abs(MIN_DECIMAL_EXPONENT)
  52     static final int    MAX_NDIGITS = 1100;
  53 
  54     static final int    SINGLE_EXP_SHIFT  =   FloatConsts.SIGNIFICAND_WIDTH - 1;
  55     static final int    SINGLE_FRACT_HOB  =   1<<SINGLE_EXP_SHIFT;
  56     static final int    SINGLE_MAX_DECIMAL_DIGITS = 7;
  57     static final int    SINGLE_MAX_DECIMAL_EXPONENT = 38;
  58     static final int    SINGLE_MIN_DECIMAL_EXPONENT = -45;
  59     static final int    SINGLE_MAX_NDIGITS = 200;
  60 
  61     static final int    INT_DECIMAL_DIGITS = 9;
  62 
  63     /**
  64      * Converts a double precision floating point value to a <code>String</code>.
  65      *
  66      * @param d The double precision value.
  67      * @return The value converted to a <code>String</code>.
  68      */
  69     public static String toJavaFormatString(double d) {
  70         return getBinaryToASCIIConverter(d).toJavaFormatString();
  71     }
  72 
  73     /**
  74      * Converts a single precision floating point value to a <code>String</code>.
  75      *
  76      * @param f The single precision value.
  77      * @return The value converted to a <code>String</code>.
  78      */
  79     public static String toJavaFormatString(float f) {
  80         return getBinaryToASCIIConverter(f).toJavaFormatString();
  81     }
  82 
  83     /**
  84      * Appends a double precision floating point value to an <code>Appendable</code>.
  85      * @param d The double precision value.
  86      * @param buf The <code>Appendable</code> with the value appended.
  87      */
  88     public static void appendTo(double d, Appendable buf) {
  89         getBinaryToASCIIConverter(d).appendTo(buf);
  90     }
  91 
  92     /**
  93      * Appends a single precision floating point value to an <code>Appendable</code>.
  94      * @param f The single precision value.
  95      * @param buf The <code>Appendable</code> with the value appended.
  96      */
  97     public static void appendTo(float f, Appendable buf) {
  98         getBinaryToASCIIConverter(f).appendTo(buf);
  99     }
 100 
 101     /**
 102      * Converts a <code>String</code> to a double precision floating point value.
 103      *
 104      * @param s The <code>String</code> to convert.
 105      * @return The double precision value.
 106      * @throws NumberFormatException If the <code>String</code> does not
 107      * represent a properly formatted double precision value.
 108      */
 109     public static double parseDouble(String s) throws NumberFormatException {
 110         return readJavaFormatString(s).doubleValue();
 111     }
 112 
 113     /**
 114      * Converts a <code>String</code> to a single precision floating point value.
 115      *
 116      * @param s The <code>String</code> to convert.
 117      * @return The single precision value.
 118      * @throws NumberFormatException If the <code>String</code> does not
 119      * represent a properly formatted single precision value.
 120      */
 121     public static float parseFloat(String s) throws NumberFormatException {
 122         return readJavaFormatString(s).floatValue();
 123     }
 124 
 125     /**
 126      * A converter which can process single or double precision floating point
 127      * values into an ASCII <code>String</code> representation.
 128      */
 129     public interface BinaryToASCIIConverter {
 130         /**
 131          * Converts a floating point value into an ASCII <code>String</code>.
 132          * @return The value converted to a <code>String</code>.
 133          */
 134         String toJavaFormatString();
 135 
 136         /**
 137          * Appends a floating point value to an <code>Appendable</code>.
 138          * @param buf The <code>Appendable</code> to receive the value.
 139          */
 140         void appendTo(Appendable buf);
 141 
 142         /**
 143          * Retrieves the decimal exponent most closely corresponding to this value.
 144          * @return The decimal exponent.
 145          */
 146         int getDecimalExponent();
 147 
 148         /**
 149          * Retrieves the value as an array of digits.
 150          * @param digits The digit array.
 151          * @return The number of valid digits copied into the array.
 152          */
 153         int getDigits(char[] digits);
 154 
 155         /**
 156          * Indicates the sign of the value.
 157          * @return {@code value < 0.0}.
 158          */
 159         boolean isNegative();
 160 
 161         /**
 162          * Indicates whether the value is either infinite or not a number.
 163          *
 164          * @return <code>true</code> if and only if the value is <code>NaN</code>
 165          * or infinite.
 166          */
 167         boolean isExceptional();
 168 
 169         /**
 170          * Indicates whether the value was rounded up during the binary to ASCII
 171          * conversion.
 172          *
 173          * @return <code>true</code> if and only if the value was rounded up.
 174          */
 175         boolean digitsRoundedUp();
 176 
 177         /**
 178          * Indicates whether the binary to ASCII conversion was exact.
 179          *
 180          * @return <code>true</code> if any only if the conversion was exact.
 181          */
 182         boolean decimalDigitsExact();
 183     }
 184 
 185     /**
 186      * A <code>BinaryToASCIIConverter</code> which represents <code>NaN</code>
 187      * and infinite values.
 188      */
 189     private static class ExceptionalBinaryToASCIIBuffer implements BinaryToASCIIConverter {
 190         private final String image;
 191         private boolean isNegative;
 192 
 193         public ExceptionalBinaryToASCIIBuffer(String image, boolean isNegative) {
 194             this.image = image;
 195             this.isNegative = isNegative;
 196         }
 197 
 198         @Override
 199         public String toJavaFormatString() {
 200             return image;
 201         }
 202 
 203         @Override
 204         public void appendTo(Appendable buf) {
 205             if (buf instanceof StringBuilder) {
 206                 ((StringBuilder) buf).append(image);
 207             } else if (buf instanceof StringBuffer) {
 208                 ((StringBuffer) buf).append(image);
 209             } else {
 210                 assert false;
 211             }
 212         }
 213 
 214         @Override
 215         public int getDecimalExponent() {
 216             throw new IllegalArgumentException("Exceptional value does not have an exponent");
 217         }
 218 
 219         @Override
 220         public int getDigits(char[] digits) {
 221             throw new IllegalArgumentException("Exceptional value does not have digits");
 222         }
 223 
 224         @Override
 225         public boolean isNegative() {
 226             return isNegative;
 227         }
 228 
 229         @Override
 230         public boolean isExceptional() {
 231             return true;
 232         }
 233 
 234         @Override
 235         public boolean digitsRoundedUp() {
 236             throw new IllegalArgumentException("Exceptional value is not rounded");
 237         }
 238 
 239         @Override
 240         public boolean decimalDigitsExact() {
 241             throw new IllegalArgumentException("Exceptional value is not exact");
 242         }
 243     }
 244 
 245     private static final String INFINITY_REP = "Infinity";
 246     private static final int INFINITY_LENGTH = INFINITY_REP.length();
 247     private static final String NAN_REP = "NaN";
 248     private static final int NAN_LENGTH = NAN_REP.length();
 249 
 250     private static final BinaryToASCIIConverter B2AC_POSITIVE_INFINITY = new ExceptionalBinaryToASCIIBuffer(INFINITY_REP, false);
 251     private static final BinaryToASCIIConverter B2AC_NEGATIVE_INFINITY = new ExceptionalBinaryToASCIIBuffer("-" + INFINITY_REP, true);
 252     private static final BinaryToASCIIConverter B2AC_NOT_A_NUMBER = new ExceptionalBinaryToASCIIBuffer(NAN_REP, false);
 253     private static final BinaryToASCIIConverter B2AC_POSITIVE_ZERO = new BinaryToASCIIBuffer(false, new char[]{'0'});
 254     private static final BinaryToASCIIConverter B2AC_NEGATIVE_ZERO = new BinaryToASCIIBuffer(true,  new char[]{'0'});
 255 
 256     /**
 257      * A buffered implementation of <code>BinaryToASCIIConverter</code>.
 258      */
 259     static class BinaryToASCIIBuffer implements BinaryToASCIIConverter {
 260         private boolean isNegative;
 261         private int decExponent;
 262         private int firstDigitIndex;
 263         private int nDigits;
 264         private final char[] digits;
 265         private final char[] buffer = new char[26];
 266 
 267         //
 268         // The fields below provide additional information about the result of
 269         // the binary to decimal digits conversion done in dtoa() and roundup()
 270         // methods. They are changed if needed by those two methods.
 271         //
 272 
 273         // True if the dtoa() binary to decimal conversion was exact.
 274         private boolean exactDecimalConversion = false;
 275 
 276         // True if the result of the binary to decimal conversion was rounded-up
 277         // at the end of the conversion process, i.e. roundUp() method was called.
 278         private boolean decimalDigitsRoundedUp = false;
 279 
 280         /**
 281          * Default constructor; used for non-zero values,
 282          * <code>BinaryToASCIIBuffer</code> may be thread-local and reused
 283          */
 284         BinaryToASCIIBuffer(){
 285             this.digits = new char[20];
 286         }
 287 
 288         /**
 289          * Creates a specialized value (positive and negative zeros).
 290          */
 291         BinaryToASCIIBuffer(boolean isNegative, char[] digits){
 292             this.isNegative = isNegative;
 293             this.decExponent  = 0;
 294             this.digits = digits;
 295             this.firstDigitIndex = 0;
 296             this.nDigits = digits.length;
 297         }
 298 
 299         @Override
 300         public String toJavaFormatString() {
 301             int len = getChars(buffer);
 302             return new String(buffer, 0, len);
 303         }
 304 
 305         @Override
 306         public void appendTo(Appendable buf) {
 307             int len = getChars(buffer);
 308             if (buf instanceof StringBuilder) {
 309                 ((StringBuilder) buf).append(buffer, 0, len);
 310             } else if (buf instanceof StringBuffer) {
 311                 ((StringBuffer) buf).append(buffer, 0, len);
 312             } else {
 313                 assert false;
 314             }
 315         }
 316 
 317         @Override
 318         public int getDecimalExponent() {
 319             return decExponent;
 320         }
 321 
 322         @Override
 323         public int getDigits(char[] digits) {
 324             System.arraycopy(this.digits, firstDigitIndex, digits, 0, this.nDigits);
 325             return this.nDigits;
 326         }
 327 
 328         @Override
 329         public boolean isNegative() {
 330             return isNegative;
 331         }
 332 
 333         @Override
 334         public boolean isExceptional() {
 335             return false;
 336         }
 337 
 338         @Override
 339         public boolean digitsRoundedUp() {
 340             return decimalDigitsRoundedUp;
 341         }
 342 
 343         @Override
 344         public boolean decimalDigitsExact() {
 345             return exactDecimalConversion;
 346         }
 347 
 348         private void setSign(boolean isNegative) {
 349             this.isNegative = isNegative;
 350         }
 351 
 352         /**
 353          * This is the easy subcase --
 354          * all the significant bits, after scaling, are held in lvalue.
 355          * negSign and decExponent tell us what processing and scaling
 356          * has already been done. Exceptional cases have already been
 357          * stripped out.
 358          * In particular:
 359          * lvalue is a finite number (not Inf, nor NaN)
 360          * lvalue > 0L (not zero, nor negative).
 361          *
 362          * The only reason that we develop the digits here, rather than
 363          * calling on Long.toString() is that we can do it a little faster,
 364          * and besides want to treat trailing 0s specially. If Long.toString
 365          * changes, we should re-evaluate this strategy!
 366          */
 367         private void developLongDigits( int decExponent, long lvalue, int insignificantDigits ){
 368             if ( insignificantDigits != 0 ){
 369                 // Discard non-significant low-order bits, while rounding,
 370                 // up to insignificant value.
 371                 long pow10 = FDBigInteger.LONG_5_POW[insignificantDigits] << insignificantDigits; // 10^i == 5^i * 2^i;
 372                 long residue = lvalue % pow10;
 373                 lvalue /= pow10;
 374                 decExponent += insignificantDigits;
 375                 if ( residue >= (pow10>>1) ){
 376                     // round up based on the low-order bits we're discarding
 377                     lvalue++;
 378                 }
 379             }
 380             int  digitno = digits.length -1;
 381             int  c;
 382             if ( lvalue <= Integer.MAX_VALUE ){
 383                 assert lvalue > 0L : lvalue; // lvalue <= 0
 384                 // even easier subcase!
 385                 // can do int arithmetic rather than long!
 386                 int  ivalue = (int)lvalue;
 387                 c = ivalue%10;
 388                 ivalue /= 10;
 389                 while ( c == 0 ){
 390                     decExponent++;
 391                     c = ivalue%10;
 392                     ivalue /= 10;
 393                 }
 394                 while ( ivalue != 0){
 395                     digits[digitno--] = (char)(c+'0');
 396                     decExponent++;
 397                     c = ivalue%10;
 398                     ivalue /= 10;
 399                 }
 400                 digits[digitno] = (char)(c+'0');
 401             } else {
 402                 // same algorithm as above (same bugs, too )
 403                 // but using long arithmetic.
 404                 c = (int)(lvalue%10L);
 405                 lvalue /= 10L;
 406                 while ( c == 0 ){
 407                     decExponent++;
 408                     c = (int)(lvalue%10L);
 409                     lvalue /= 10L;
 410                 }
 411                 while ( lvalue != 0L ){
 412                     digits[digitno--] = (char)(c+'0');
 413                     decExponent++;
 414                     c = (int)(lvalue%10L);
 415                     lvalue /= 10;
 416                 }
 417                 digits[digitno] = (char)(c+'0');
 418             }
 419             this.decExponent = decExponent+1;
 420             this.firstDigitIndex = digitno;
 421             this.nDigits = this.digits.length - digitno;
 422         }
 423 
 424         private void dtoa( int binExp, long fractBits, int nSignificantBits, boolean isCompatibleFormat)
 425         {
 426             assert fractBits > 0 ; // fractBits here can't be zero or negative
 427             assert (fractBits & FRACT_HOB)!=0  ; // Hi-order bit should be set
 428             // Examine number. Determine if it is an easy case,
 429             // which we can do pretty trivially using float/long conversion,
 430             // or whether we must do real work.
 431             final int tailZeros = Long.numberOfTrailingZeros(fractBits);
 432 
 433             // number of significant bits of fractBits;
 434             final int nFractBits = EXP_SHIFT+1-tailZeros;
 435 
 436             // reset flags to default values as dtoa() does not always set these
 437             // flags and a prior call to dtoa() might have set them to incorrect
 438             // values with respect to the current state.
 439             decimalDigitsRoundedUp = false;
 440             exactDecimalConversion = false;
 441 
 442             // number of significant bits to the right of the point.
 443             int nTinyBits = Math.max( 0, nFractBits - binExp - 1 );
 444             if ( binExp <= MAX_SMALL_BIN_EXP && binExp >= MIN_SMALL_BIN_EXP ){
 445                 // Look more closely at the number to decide if,
 446                 // with scaling by 10^nTinyBits, the result will fit in
 447                 // a long.
 448                 if ( (nTinyBits < FDBigInteger.LONG_5_POW.length) && ((nFractBits + N_5_BITS[nTinyBits]) < 64 ) ){
 449                     //
 450                     // We can do this:
 451                     // take the fraction bits, which are normalized.
 452                     // (a) nTinyBits == 0: Shift left or right appropriately
 453                     //     to align the binary point at the extreme right, i.e.
 454                     //     where a long int point is expected to be. The integer
 455                     //     result is easily converted to a string.
 456                     // (b) nTinyBits > 0: Shift right by EXP_SHIFT-nFractBits,
 457                     //     which effectively converts to long and scales by
 458                     //     2^nTinyBits. Then multiply by 5^nTinyBits to
 459                     //     complete the scaling. We know this won't overflow
 460                     //     because we just counted the number of bits necessary
 461                     //     in the result. The integer you get from this can
 462                     //     then be converted to a string pretty easily.
 463                     //
 464                     if ( nTinyBits == 0 ) {
 465                         int insignificant;
 466                         if ( binExp > nSignificantBits ){
 467                             insignificant = insignificantDigitsForPow2(binExp-nSignificantBits-1);
 468                         } else {
 469                             insignificant = 0;
 470                         }
 471                         if ( binExp >= EXP_SHIFT ){
 472                             fractBits <<= (binExp-EXP_SHIFT);
 473                         } else {
 474                             fractBits >>>= (EXP_SHIFT-binExp) ;
 475                         }
 476                         developLongDigits( 0, fractBits, insignificant );
 477                         return;
 478                     }
 479                     //
 480                     // The following causes excess digits to be printed
 481                     // out in the single-float case. Our manipulation of
 482                     // halfULP here is apparently not correct. If we
 483                     // better understand how this works, perhaps we can
 484                     // use this special case again. But for the time being,
 485                     // we do not.
 486                     // else {
 487                     //     fractBits >>>= EXP_SHIFT+1-nFractBits;
 488                     //     fractBits//= long5pow[ nTinyBits ];
 489                     //     halfULP = long5pow[ nTinyBits ] >> (1+nSignificantBits-nFractBits);
 490                     //     developLongDigits( -nTinyBits, fractBits, insignificantDigits(halfULP) );
 491                     //     return;
 492                     // }
 493                     //
 494                 }
 495             }
 496             //
 497             // This is the hard case. We are going to compute large positive
 498             // integers B and S and integer decExp, s.t.
 499             //      d = ( B / S )// 10^decExp
 500             //      1 <= B / S < 10
 501             // Obvious choices are:
 502             //      decExp = floor( log10(d) )
 503             //      B      = d// 2^nTinyBits// 10^max( 0, -decExp )
 504             //      S      = 10^max( 0, decExp)// 2^nTinyBits
 505             // (noting that nTinyBits has already been forced to non-negative)
 506             // I am also going to compute a large positive integer
 507             //      M      = (1/2^nSignificantBits)// 2^nTinyBits// 10^max( 0, -decExp )
 508             // i.e. M is (1/2) of the ULP of d, scaled like B.
 509             // When we iterate through dividing B/S and picking off the
 510             // quotient bits, we will know when to stop when the remainder
 511             // is <= M.
 512             //
 513             // We keep track of powers of 2 and powers of 5.
 514             //
 515             int decExp = estimateDecExp(fractBits,binExp);
 516             int B2, B5; // powers of 2 and powers of 5, respectively, in B
 517             int S2, S5; // powers of 2 and powers of 5, respectively, in S
 518             int M2, M5; // powers of 2 and powers of 5, respectively, in M
 519 
 520             B5 = Math.max( 0, -decExp );
 521             B2 = B5 + nTinyBits + binExp;
 522 
 523             S5 = Math.max( 0, decExp );
 524             S2 = S5 + nTinyBits;
 525 
 526             M5 = B5;
 527             M2 = B2 - nSignificantBits;
 528 
 529             //
 530             // the long integer fractBits contains the (nFractBits) interesting
 531             // bits from the mantissa of d ( hidden 1 added if necessary) followed
 532             // by (EXP_SHIFT+1-nFractBits) zeros. In the interest of compactness,
 533             // I will shift out those zeros before turning fractBits into a
 534             // FDBigInteger. The resulting whole number will be
 535             //      d * 2^(nFractBits-1-binExp).
 536             //
 537             fractBits >>>= tailZeros;
 538             B2 -= nFractBits-1;
 539             int common2factor = Math.min( B2, S2 );
 540             B2 -= common2factor;
 541             S2 -= common2factor;
 542             M2 -= common2factor;
 543 
 544             //
 545             // HACK!! For exact powers of two, the next smallest number
 546             // is only half as far away as we think (because the meaning of
 547             // ULP changes at power-of-two bounds) for this reason, we
 548             // hack M2. Hope this works.
 549             //
 550             if ( nFractBits == 1 ) {
 551                 M2 -= 1;
 552             }
 553 
 554             if ( M2 < 0 ){
 555                 // oops.
 556                 // since we cannot scale M down far enough,
 557                 // we must scale the other values up.
 558                 B2 -= M2;
 559                 S2 -= M2;
 560                 M2 =  0;
 561             }
 562             //
 563             // Construct, Scale, iterate.
 564             // Some day, we'll write a stopping test that takes
 565             // account of the asymmetry of the spacing of floating-point
 566             // numbers below perfect powers of 2
 567             // 26 Sept 96 is not that day.
 568             // So we use a symmetric test.
 569             //
 570             int ndigit = 0;
 571             boolean low, high;
 572             long lowDigitDifference;
 573             int  q;
 574 
 575             //
 576             // Detect the special cases where all the numbers we are about
 577             // to compute will fit in int or long integers.
 578             // In these cases, we will avoid doing FDBigInteger arithmetic.
 579             // We use the same algorithms, except that we "normalize"
 580             // our FDBigIntegers before iterating. This is to make division easier,
 581             // as it makes our fist guess (quotient of high-order words)
 582             // more accurate!
 583             //
 584             // Some day, we'll write a stopping test that takes
 585             // account of the asymmetry of the spacing of floating-point
 586             // numbers below perfect powers of 2
 587             // 26 Sept 96 is not that day.
 588             // So we use a symmetric test.
 589             //
 590             // binary digits needed to represent B, approx.
 591             int Bbits = nFractBits + B2 + (( B5 < N_5_BITS.length )? N_5_BITS[B5] : ( B5*3 ));
 592 
 593             // binary digits needed to represent 10*S, approx.
 594             int tenSbits = S2+1 + (( (S5+1) < N_5_BITS.length )? N_5_BITS[(S5+1)] : ( (S5+1)*3 ));
 595             if ( Bbits < 64 && tenSbits < 64){
 596                 if ( Bbits < 32 && tenSbits < 32){
 597                     // wa-hoo! They're all ints!
 598                     int b = ((int)fractBits * FDBigInteger.SMALL_5_POW[B5] ) << B2;
 599                     int s = FDBigInteger.SMALL_5_POW[S5] << S2;
 600                     int m = FDBigInteger.SMALL_5_POW[M5] << M2;
 601                     int tens = s * 10;
 602                     //
 603                     // Unroll the first iteration. If our decExp estimate
 604                     // was too high, our first quotient will be zero. In this
 605                     // case, we discard it and decrement decExp.
 606                     //
 607                     ndigit = 0;
 608                     q = b / s;
 609                     b = 10 * ( b % s );
 610                     m *= 10;
 611                     low  = (b <  m );
 612                     high = (b+m > tens );
 613                     assert q < 10 : q; // excessively large digit
 614                     if ( (q == 0) && ! high ){
 615                         // oops. Usually ignore leading zero.
 616                         decExp--;
 617                     } else {
 618                         digits[ndigit++] = (char)('0' + q);
 619                     }
 620                     //
 621                     // HACK! Java spec sez that we always have at least
 622                     // one digit after the . in either F- or E-form output.
 623                     // Thus we will need more than one digit if we're using
 624                     // E-form
 625                     //
 626                     if ( !isCompatibleFormat ||decExp < -3 || decExp >= 8 ){
 627                         high = low = false;
 628                     }
 629                     while( ! low && ! high ){
 630                         q = b / s;
 631                         b = 10 * ( b % s );
 632                         m *= 10;
 633                         assert q < 10 : q; // excessively large digit
 634                         if ( m > 0L ){
 635                             low  = (b <  m );
 636                             high = (b+m > tens );
 637                         } else {
 638                             // hack -- m might overflow!
 639                             // in this case, it is certainly > b,
 640                             // which won't
 641                             // and b+m > tens, too, since that has overflowed
 642                             // either!
 643                             low = true;
 644                             high = true;
 645                         }
 646                         digits[ndigit++] = (char)('0' + q);
 647                     }
 648                     lowDigitDifference = (b<<1) - tens;
 649                     exactDecimalConversion  = (b == 0);
 650                 } else {
 651                     // still good! they're all longs!
 652                     long b = (fractBits * FDBigInteger.LONG_5_POW[B5] ) << B2;
 653                     long s = FDBigInteger.LONG_5_POW[S5] << S2;
 654                     long m = FDBigInteger.LONG_5_POW[M5] << M2;
 655                     long tens = s * 10L;
 656                     //
 657                     // Unroll the first iteration. If our decExp estimate
 658                     // was too high, our first quotient will be zero. In this
 659                     // case, we discard it and decrement decExp.
 660                     //
 661                     ndigit = 0;
 662                     q = (int) ( b / s );
 663                     b = 10L * ( b % s );
 664                     m *= 10L;
 665                     low  = (b <  m );
 666                     high = (b+m > tens );
 667                     assert q < 10 : q; // excessively large digit
 668                     if ( (q == 0) && ! high ){
 669                         // oops. Usually ignore leading zero.
 670                         decExp--;
 671                     } else {
 672                         digits[ndigit++] = (char)('0' + q);
 673                     }
 674                     //
 675                     // HACK! Java spec sez that we always have at least
 676                     // one digit after the . in either F- or E-form output.
 677                     // Thus we will need more than one digit if we're using
 678                     // E-form
 679                     //
 680                     if ( !isCompatibleFormat || decExp < -3 || decExp >= 8 ){
 681                         high = low = false;
 682                     }
 683                     while( ! low && ! high ){
 684                         q = (int) ( b / s );
 685                         b = 10 * ( b % s );
 686                         m *= 10;
 687                         assert q < 10 : q;  // excessively large digit
 688                         if ( m > 0L ){
 689                             low  = (b <  m );
 690                             high = (b+m > tens );
 691                         } else {
 692                             // hack -- m might overflow!
 693                             // in this case, it is certainly > b,
 694                             // which won't
 695                             // and b+m > tens, too, since that has overflowed
 696                             // either!
 697                             low = true;
 698                             high = true;
 699                         }
 700                         digits[ndigit++] = (char)('0' + q);
 701                     }
 702                     lowDigitDifference = (b<<1) - tens;
 703                     exactDecimalConversion  = (b == 0);
 704                 }
 705             } else {
 706                 //
 707                 // We really must do FDBigInteger arithmetic.
 708                 // Fist, construct our FDBigInteger initial values.
 709                 //
 710                 FDBigInteger Sval = FDBigInteger.valueOfPow52(S5, S2);
 711                 int shiftBias = Sval.getNormalizationBias();
 712                 Sval = Sval.leftShift(shiftBias); // normalize so that division works better
 713 
 714                 FDBigInteger Bval = FDBigInteger.valueOfMulPow52(fractBits, B5, B2 + shiftBias);
 715                 FDBigInteger Mval = FDBigInteger.valueOfPow52(M5 + 1, M2 + shiftBias + 1);
 716 
 717                 FDBigInteger tenSval = FDBigInteger.valueOfPow52(S5 + 1, S2 + shiftBias + 1); //Sval.mult( 10 );
 718                 //
 719                 // Unroll the first iteration. If our decExp estimate
 720                 // was too high, our first quotient will be zero. In this
 721                 // case, we discard it and decrement decExp.
 722                 //
 723                 ndigit = 0;
 724                 q = Bval.quoRemIteration( Sval );
 725                 low  = (Bval.cmp( Mval ) < 0);
 726                 high = tenSval.addAndCmp(Bval,Mval)<=0;
 727 
 728                 assert q < 10 : q; // excessively large digit
 729                 if ( (q == 0) && ! high ){
 730                     // oops. Usually ignore leading zero.
 731                     decExp--;
 732                 } else {
 733                     digits[ndigit++] = (char)('0' + q);
 734                 }
 735                 //
 736                 // HACK! Java spec sez that we always have at least
 737                 // one digit after the . in either F- or E-form output.
 738                 // Thus we will need more than one digit if we're using
 739                 // E-form
 740                 //
 741                 if (!isCompatibleFormat || decExp < -3 || decExp >= 8 ){
 742                     high = low = false;
 743                 }
 744                 while( ! low && ! high ){
 745                     q = Bval.quoRemIteration( Sval );
 746                     assert q < 10 : q;  // excessively large digit
 747                     Mval = Mval.multBy10(); //Mval = Mval.mult( 10 );
 748                     low  = (Bval.cmp( Mval ) < 0);
 749                     high = tenSval.addAndCmp(Bval,Mval)<=0;
 750                     digits[ndigit++] = (char)('0' + q);
 751                 }
 752                 if ( high && low ){
 753                     Bval = Bval.leftShift(1);
 754                     lowDigitDifference = Bval.cmp(tenSval);
 755                 } else {
 756                     lowDigitDifference = 0L; // this here only for flow analysis!
 757                 }
 758                 exactDecimalConversion  = (Bval.cmp( FDBigInteger.ZERO ) == 0);
 759             }
 760             this.decExponent = decExp+1;
 761             this.firstDigitIndex = 0;
 762             this.nDigits = ndigit;
 763             //
 764             // Last digit gets rounded based on stopping condition.
 765             //
 766             if ( high ){
 767                 if ( low ){
 768                     if ( lowDigitDifference == 0L ){
 769                         // it's a tie!
 770                         // choose based on which digits we like.
 771                         if ( (digits[firstDigitIndex+nDigits-1]&1) != 0 ) {
 772                             roundup();
 773                         }
 774                     } else if ( lowDigitDifference > 0 ){
 775                         roundup();
 776                     }
 777                 } else {
 778                     roundup();
 779                 }
 780             }
 781         }
 782 
 783         // add one to the least significant digit.
 784         // in the unlikely event there is a carry out, deal with it.
 785         // assert that this will only happen where there
 786         // is only one digit, e.g. (float)1e-44 seems to do it.
 787         //
 788         private void roundup() {
 789             int i = (firstDigitIndex + nDigits - 1);
 790             int q = digits[i];
 791             if (q == '9') {
 792                 while (q == '9' && i > firstDigitIndex) {
 793                     digits[i] = '0';
 794                     q = digits[--i];
 795                 }
 796                 if (q == '9') {
 797                     // carryout! High-order 1, rest 0s, larger exp.
 798                     decExponent += 1;
 799                     digits[firstDigitIndex] = '1';
 800                     return;
 801                 }
 802                 // else fall through.
 803             }
 804             digits[i] = (char) (q + 1);
 805             decimalDigitsRoundedUp = true;
 806         }
 807 
 808         /**
 809          * Estimate decimal exponent. (If it is small-ish,
 810          * we could double-check.)
 811          *
 812          * First, scale the mantissa bits such that 1 <= d2 < 2.
 813          * We are then going to estimate
 814          *          log10(d2) ~=~  (d2-1.5)/1.5 + log(1.5)
 815          * and so we can estimate
 816          *      log10(d) ~=~ log10(d2) + binExp * log10(2)
 817          * take the floor and call it decExp.
 818          */
 819         static int estimateDecExp(long fractBits, int binExp) {
 820             double d2 = Double.longBitsToDouble( EXP_ONE | ( fractBits & DoubleConsts.SIGNIF_BIT_MASK ) );
 821             double d = (d2-1.5D)*0.289529654D + 0.176091259 + (double)binExp * 0.301029995663981;
 822             long dBits = Double.doubleToRawLongBits(d);  //can't be NaN here so use raw
 823             int exponent = (int)((dBits & DoubleConsts.EXP_BIT_MASK) >> EXP_SHIFT) - DoubleConsts.EXP_BIAS;
 824             boolean isNegative = (dBits & DoubleConsts.SIGN_BIT_MASK) != 0; // discover sign
 825             if(exponent>=0 && exponent<52) { // hot path
 826                 long mask   = DoubleConsts.SIGNIF_BIT_MASK >> exponent;
 827                 int r = (int)(( (dBits&DoubleConsts.SIGNIF_BIT_MASK) | FRACT_HOB )>>(EXP_SHIFT-exponent));
 828                 return isNegative ? (((mask & dBits) == 0L ) ? -r : -r-1 ) : r;
 829             } else if (exponent < 0) {
 830                 return (((dBits&~DoubleConsts.SIGN_BIT_MASK) == 0) ? 0 :
 831                         ( (isNegative) ? -1 : 0) );
 832             } else { //if (exponent >= 52)
 833                 return (int)d;
 834             }
 835         }
 836 
 837         private static int insignificantDigits(int insignificant) {
 838             int i;
 839             for ( i = 0; insignificant >= 10L; i++ ) {
 840                 insignificant /= 10L;
 841             }
 842             return i;
 843         }
 844 
 845         /**
 846          * Calculates
 847          * <pre>
 848          * insignificantDigitsForPow2(v) == insignificantDigits(1L<<v)
 849          * </pre>
 850          */
 851         private static int insignificantDigitsForPow2(int p2) {
 852             if (p2 > 1 && p2 < insignificantDigitsNumber.length) {
 853                 return insignificantDigitsNumber[p2];
 854             }
 855             return 0;
 856         }
 857 
 858         /**
 859          *  If insignificant==(1L << ixd)
 860          *  i = insignificantDigitsNumber[idx] is the same as:
 861          *  int i;
 862          *  for ( i = 0; insignificant >= 10L; i++ )
 863          *         insignificant /= 10L;
 864          */
 865         private static final int[] insignificantDigitsNumber = {
 866             0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3,
 867             4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7,
 868             8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 11, 11, 11,
 869             12, 12, 12, 12, 13, 13, 13, 14, 14, 14,
 870             15, 15, 15, 15, 16, 16, 16, 17, 17, 17,
 871             18, 18, 18, 19
 872         };
 873 
 874         // approximately ceil( log2( long5pow[i] ) )
 875         private static final int[] N_5_BITS = {
 876                 0,
 877                 3,
 878                 5,
 879                 7,
 880                 10,
 881                 12,
 882                 14,
 883                 17,
 884                 19,
 885                 21,
 886                 24,
 887                 26,
 888                 28,
 889                 31,
 890                 33,
 891                 35,
 892                 38,
 893                 40,
 894                 42,
 895                 45,
 896                 47,
 897                 49,
 898                 52,
 899                 54,
 900                 56,
 901                 59,
 902                 61,
 903         };
 904 
 905         private int getChars(char[] result) {
 906             assert nDigits <= 19 : nDigits; // generous bound on size of nDigits
 907             int i = 0;
 908             if (isNegative) {
 909                 result[0] = '-';
 910                 i = 1;
 911             }
 912             if (decExponent > 0 && decExponent < 8) {
 913                 // print digits.digits.
 914                 int charLength = Math.min(nDigits, decExponent);
 915                 System.arraycopy(digits, firstDigitIndex, result, i, charLength);
 916                 i += charLength;
 917                 if (charLength < decExponent) {
 918                     charLength = decExponent - charLength;
 919                     Arrays.fill(result,i,i+charLength,'0');
 920                     i += charLength;
 921                     result[i++] = '.';
 922                     result[i++] = '0';
 923                 } else {
 924                     result[i++] = '.';
 925                     if (charLength < nDigits) {
 926                         int t = nDigits - charLength;
 927                         System.arraycopy(digits, firstDigitIndex+charLength, result, i, t);
 928                         i += t;
 929                     } else {
 930                         result[i++] = '0';
 931                     }
 932                 }
 933             } else if (decExponent <= 0 && decExponent > -3) {
 934                 result[i++] = '0';
 935                 result[i++] = '.';
 936                 if (decExponent != 0) {
 937                     Arrays.fill(result, i, i-decExponent, '0');
 938                     i -= decExponent;
 939                 }
 940                 System.arraycopy(digits, firstDigitIndex, result, i, nDigits);
 941                 i += nDigits;
 942             } else {
 943                 result[i++] = digits[firstDigitIndex];
 944                 result[i++] = '.';
 945                 if (nDigits > 1) {
 946                     System.arraycopy(digits, firstDigitIndex+1, result, i, nDigits - 1);
 947                     i += nDigits - 1;
 948                 } else {
 949                     result[i++] = '0';
 950                 }
 951                 result[i++] = 'E';
 952                 int e;
 953                 if (decExponent <= 0) {
 954                     result[i++] = '-';
 955                     e = -decExponent + 1;
 956                 } else {
 957                     e = decExponent - 1;
 958                 }
 959                 // decExponent has 1, 2, or 3, digits
 960                 if (e <= 9) {
 961                     result[i++] = (char) (e + '0');
 962                 } else if (e <= 99) {
 963                     result[i++] = (char) (e / 10 + '0');
 964                     result[i++] = (char) (e % 10 + '0');
 965                 } else {
 966                     result[i++] = (char) (e / 100 + '0');
 967                     e %= 100;
 968                     result[i++] = (char) (e / 10 + '0');
 969                     result[i++] = (char) (e % 10 + '0');
 970                 }
 971             }
 972             return i;
 973         }
 974 
 975     }
 976 
 977     private static final ThreadLocal<BinaryToASCIIBuffer> threadLocalBinaryToASCIIBuffer =
 978             new ThreadLocal<BinaryToASCIIBuffer>() {
 979                 @Override
 980                 protected BinaryToASCIIBuffer initialValue() {
 981                     return new BinaryToASCIIBuffer();
 982                 }
 983             };
 984 
 985     private static BinaryToASCIIBuffer getBinaryToASCIIBuffer() {
 986         if (Thread.currentThread().isVirtual()) {
 987             return new BinaryToASCIIBuffer();
 988         } else {
 989             return threadLocalBinaryToASCIIBuffer.get();
 990         }
 991     }
 992 
 993     /**
 994      * A converter which can process an ASCII <code>String</code> representation
 995      * of a single or double precision floating point value into a
 996      * <code>float</code> or a <code>double</code>.
 997      */
 998     interface ASCIIToBinaryConverter {
 999 
1000         double doubleValue();
1001 
1002         float floatValue();
1003 
1004     }
1005 
1006     /**
1007      * A <code>ASCIIToBinaryConverter</code> container for a <code>double</code>.
1008      */
1009     static class PreparedASCIIToBinaryBuffer implements ASCIIToBinaryConverter {
1010         private final double doubleVal;
1011         private final float floatVal;
1012 
1013         public PreparedASCIIToBinaryBuffer(double doubleVal, float floatVal) {
1014             this.doubleVal = doubleVal;
1015             this.floatVal = floatVal;
1016         }
1017 
1018         @Override
1019         public double doubleValue() {
1020             return doubleVal;
1021         }
1022 
1023         @Override
1024         public float floatValue() {
1025             return floatVal;
1026         }
1027     }
1028 
1029     static final ASCIIToBinaryConverter A2BC_POSITIVE_INFINITY = new PreparedASCIIToBinaryBuffer(Double.POSITIVE_INFINITY, Float.POSITIVE_INFINITY);
1030     static final ASCIIToBinaryConverter A2BC_NEGATIVE_INFINITY = new PreparedASCIIToBinaryBuffer(Double.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY);
1031     static final ASCIIToBinaryConverter A2BC_NOT_A_NUMBER  = new PreparedASCIIToBinaryBuffer(Double.NaN, Float.NaN);
1032     static final ASCIIToBinaryConverter A2BC_POSITIVE_ZERO = new PreparedASCIIToBinaryBuffer(0.0d, 0.0f);
1033     static final ASCIIToBinaryConverter A2BC_NEGATIVE_ZERO = new PreparedASCIIToBinaryBuffer(-0.0d, -0.0f);
1034 
1035     /**
1036      * A buffered implementation of <code>ASCIIToBinaryConverter</code>.
1037      */
1038     static class ASCIIToBinaryBuffer implements ASCIIToBinaryConverter {
1039         boolean     isNegative;
1040         int         decExponent;
1041         char        digits[];
1042         int         nDigits;
1043 
1044         ASCIIToBinaryBuffer( boolean negSign, int decExponent, char[] digits, int n)
1045         {
1046             this.isNegative = negSign;
1047             this.decExponent = decExponent;
1048             this.digits = digits;
1049             this.nDigits = n;
1050         }
1051 
1052         /**
1053          * Takes a FloatingDecimal, which we presumably just scanned in,
1054          * and finds out what its value is, as a double.
1055          *
1056          * AS A SIDE EFFECT, SET roundDir TO INDICATE PREFERRED
1057          * ROUNDING DIRECTION in case the result is really destined
1058          * for a single-precision float.
1059          */
1060         @Override
1061         public double doubleValue() {
1062             int kDigits = Math.min(nDigits, MAX_DECIMAL_DIGITS + 1);
1063             //
1064             // convert the lead kDigits to a long integer.
1065             //
1066             // (special performance hack: start to do it using int)
1067             int iValue = (int) digits[0] - (int) '0';
1068             int iDigits = Math.min(kDigits, INT_DECIMAL_DIGITS);
1069             for (int i = 1; i < iDigits; i++) {
1070                 iValue = iValue * 10 + (int) digits[i] - (int) '0';
1071             }
1072             long lValue = (long) iValue;
1073             for (int i = iDigits; i < kDigits; i++) {
1074                 lValue = lValue * 10L + (long) ((int) digits[i] - (int) '0');
1075             }
1076             double dValue = (double) lValue;
1077             int exp = decExponent - kDigits;
1078             //
1079             // lValue now contains a long integer with the value of
1080             // the first kDigits digits of the number.
1081             // dValue contains the (double) of the same.
1082             //
1083 
1084             if (nDigits <= MAX_DECIMAL_DIGITS) {
1085                 //
1086                 // possibly an easy case.
1087                 // We know that the digits can be represented
1088                 // exactly. And if the exponent isn't too outrageous,
1089                 // the whole thing can be done with one operation,
1090                 // thus one rounding error.
1091                 // Note that all our constructors trim all leading and
1092                 // trailing zeros, so simple values (including zero)
1093                 // will always end up here
1094                 //
1095                 if (exp == 0 || dValue == 0.0) {
1096                     return (isNegative) ? -dValue : dValue; // small floating integer
1097                 }
1098                 else if (exp >= 0) {
1099                     if (exp <= MAX_SMALL_TEN) {
1100                         //
1101                         // Can get the answer with one operation,
1102                         // thus one roundoff.
1103                         //
1104                         double rValue = dValue * SMALL_10_POW[exp];
1105                         return (isNegative) ? -rValue : rValue;
1106                     }
1107                     int slop = MAX_DECIMAL_DIGITS - kDigits;
1108                     if (exp <= MAX_SMALL_TEN + slop) {
1109                         //
1110                         // We can multiply dValue by 10^(slop)
1111                         // and it is still "small" and exact.
1112                         // Then we can multiply by 10^(exp-slop)
1113                         // with one rounding.
1114                         //
1115                         dValue *= SMALL_10_POW[slop];
1116                         double rValue = dValue * SMALL_10_POW[exp - slop];
1117                         return (isNegative) ? -rValue : rValue;
1118                     }
1119                     //
1120                     // Else we have a hard case with a positive exp.
1121                     //
1122                 } else {
1123                     if (exp >= -MAX_SMALL_TEN) {
1124                         //
1125                         // Can get the answer in one division.
1126                         //
1127                         double rValue = dValue / SMALL_10_POW[-exp];
1128                         return (isNegative) ? -rValue : rValue;
1129                     }
1130                     //
1131                     // Else we have a hard case with a negative exp.
1132                     //
1133                 }
1134             }
1135 
1136             //
1137             // Harder cases:
1138             // The sum of digits plus exponent is greater than
1139             // what we think we can do with one error.
1140             //
1141             // Start by approximating the right answer by,
1142             // naively, scaling by powers of 10.
1143             //
1144             if (exp > 0) {
1145                 if (decExponent > MAX_DECIMAL_EXPONENT + 1) {
1146                     //
1147                     // Lets face it. This is going to be
1148                     // Infinity. Cut to the chase.
1149                     //
1150                     return (isNegative) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
1151                 }
1152                 if ((exp & 15) != 0) {
1153                     dValue *= SMALL_10_POW[exp & 15];
1154                 }
1155                 if ((exp >>= 4) != 0) {
1156                     int j;
1157                     for (j = 0; exp > 1; j++, exp >>= 1) {
1158                         if ((exp & 1) != 0) {
1159                             dValue *= BIG_10_POW[j];
1160                         }
1161                     }
1162                     //
1163                     // The reason for the weird exp > 1 condition
1164                     // in the above loop was so that the last multiply
1165                     // would get unrolled. We handle it here.
1166                     // It could overflow.
1167                     //
1168                     double t = dValue * BIG_10_POW[j];
1169                     if (Double.isInfinite(t)) {
1170                         //
1171                         // It did overflow.
1172                         // Look more closely at the result.
1173                         // If the exponent is just one too large,
1174                         // then use the maximum finite as our estimate
1175                         // value. Else call the result infinity
1176                         // and punt it.
1177                         // ( I presume this could happen because
1178                         // rounding forces the result here to be
1179                         // an ULP or two larger than
1180                         // Double.MAX_VALUE ).
1181                         //
1182                         t = dValue / 2.0;
1183                         t *= BIG_10_POW[j];
1184                         if (Double.isInfinite(t)) {
1185                             return (isNegative) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
1186                         }
1187                         t = Double.MAX_VALUE;
1188                     }
1189                     dValue = t;
1190                 }
1191             } else if (exp < 0) {
1192                 exp = -exp;
1193                 if (decExponent < MIN_DECIMAL_EXPONENT - 1) {
1194                     //
1195                     // Lets face it. This is going to be
1196                     // zero. Cut to the chase.
1197                     //
1198                     return (isNegative) ? -0.0 : 0.0;
1199                 }
1200                 if ((exp & 15) != 0) {
1201                     dValue /= SMALL_10_POW[exp & 15];
1202                 }
1203                 if ((exp >>= 4) != 0) {
1204                     int j;
1205                     for (j = 0; exp > 1; j++, exp >>= 1) {
1206                         if ((exp & 1) != 0) {
1207                             dValue *= TINY_10_POW[j];
1208                         }
1209                     }
1210                     //
1211                     // The reason for the weird exp > 1 condition
1212                     // in the above loop was so that the last multiply
1213                     // would get unrolled. We handle it here.
1214                     // It could underflow.
1215                     //
1216                     double t = dValue * TINY_10_POW[j];
1217                     if (t == 0.0) {
1218                         //
1219                         // It did underflow.
1220                         // Look more closely at the result.
1221                         // If the exponent is just one too small,
1222                         // then use the minimum finite as our estimate
1223                         // value. Else call the result 0.0
1224                         // and punt it.
1225                         // ( I presume this could happen because
1226                         // rounding forces the result here to be
1227                         // an ULP or two less than
1228                         // Double.MIN_VALUE ).
1229                         //
1230                         t = dValue * 2.0;
1231                         t *= TINY_10_POW[j];
1232                         if (t == 0.0) {
1233                             return (isNegative) ? -0.0 : 0.0;
1234                         }
1235                         t = Double.MIN_VALUE;
1236                     }
1237                     dValue = t;
1238                 }
1239             }
1240 
1241             //
1242             // dValue is now approximately the result.
1243             // The hard part is adjusting it, by comparison
1244             // with FDBigInteger arithmetic.
1245             // Formulate the EXACT big-number result as
1246             // bigD0 * 10^exp
1247             //
1248             if (nDigits > MAX_NDIGITS) {
1249                 nDigits = MAX_NDIGITS + 1;
1250                 digits[MAX_NDIGITS] = '1';
1251             }
1252             FDBigInteger bigD0 = new FDBigInteger(lValue, digits, kDigits, nDigits);
1253             exp = decExponent - nDigits;
1254 
1255             long ieeeBits = Double.doubleToRawLongBits(dValue); // IEEE-754 bits of double candidate
1256             final int B5 = Math.max(0, -exp); // powers of 5 in bigB, value is not modified inside correctionLoop
1257             final int D5 = Math.max(0, exp); // powers of 5 in bigD, value is not modified inside correctionLoop
1258             bigD0 = bigD0.multByPow52(D5, 0);
1259             bigD0.makeImmutable();   // prevent bigD0 modification inside correctionLoop
1260             FDBigInteger bigD = null;
1261             int prevD2 = 0;
1262 
1263             correctionLoop:
1264             while (true) {
1265                 // here ieeeBits can't be NaN, Infinity or zero
1266                 int binexp = (int) (ieeeBits >>> EXP_SHIFT);
1267                 long bigBbits = ieeeBits & DoubleConsts.SIGNIF_BIT_MASK;
1268                 if (binexp > 0) {
1269                     bigBbits |= FRACT_HOB;
1270                 } else { // Normalize denormalized numbers.
1271                     assert bigBbits != 0L : bigBbits; // doubleToBigInt(0.0)
1272                     int leadingZeros = Long.numberOfLeadingZeros(bigBbits);
1273                     int shift = leadingZeros - (63 - EXP_SHIFT);
1274                     bigBbits <<= shift;
1275                     binexp = 1 - shift;
1276                 }
1277                 binexp -= DoubleConsts.EXP_BIAS;
1278                 int lowOrderZeros = Long.numberOfTrailingZeros(bigBbits);
1279                 bigBbits >>>= lowOrderZeros;
1280                 final int bigIntExp = binexp - EXP_SHIFT + lowOrderZeros;
1281                 final int bigIntNBits = EXP_SHIFT + 1 - lowOrderZeros;
1282 
1283                 //
1284                 // Scale bigD, bigB appropriately for
1285                 // big-integer operations.
1286                 // Naively, we multiply by powers of ten
1287                 // and powers of two. What we actually do
1288                 // is keep track of the powers of 5 and
1289                 // powers of 2 we would use, then factor out
1290                 // common divisors before doing the work.
1291                 //
1292                 int B2 = B5; // powers of 2 in bigB
1293                 int D2 = D5; // powers of 2 in bigD
1294                 int Ulp2;   // powers of 2 in halfUlp.
1295                 if (bigIntExp >= 0) {
1296                     B2 += bigIntExp;
1297                 } else {
1298                     D2 -= bigIntExp;
1299                 }
1300                 Ulp2 = B2;
1301                 // shift bigB and bigD left by a number s. t.
1302                 // halfUlp is still an integer.
1303                 int hulpbias;
1304                 if (binexp <= -DoubleConsts.EXP_BIAS) {
1305                     // This is going to be a denormalized number
1306                     // (if not actually zero).
1307                     // half an ULP is at 2^-(DoubleConsts.EXP_BIAS+EXP_SHIFT+1)
1308                     hulpbias = binexp + lowOrderZeros + DoubleConsts.EXP_BIAS;
1309                 } else {
1310                     hulpbias = 1 + lowOrderZeros;
1311                 }
1312                 B2 += hulpbias;
1313                 D2 += hulpbias;
1314                 // if there are common factors of 2, we might just as well
1315                 // factor them out, as they add nothing useful.
1316                 int common2 = Math.min(B2, Math.min(D2, Ulp2));
1317                 B2 -= common2;
1318                 D2 -= common2;
1319                 Ulp2 -= common2;
1320                 // do multiplications by powers of 5 and 2
1321                 FDBigInteger bigB = FDBigInteger.valueOfMulPow52(bigBbits, B5, B2);
1322                 if (bigD == null || prevD2 != D2) {
1323                     bigD = bigD0.leftShift(D2);
1324                     prevD2 = D2;
1325                 }
1326                 //
1327                 // to recap:
1328                 // bigB is the scaled-big-int version of our floating-point
1329                 // candidate.
1330                 // bigD is the scaled-big-int version of the exact value
1331                 // as we understand it.
1332                 // halfUlp is 1/2 an ulp of bigB, except for special cases
1333                 // of exact powers of 2
1334                 //
1335                 // the plan is to compare bigB with bigD, and if the difference
1336                 // is less than halfUlp, then we're satisfied. Otherwise,
1337                 // use the ratio of difference to halfUlp to calculate a fudge
1338                 // factor to add to the floating value, then go 'round again.
1339                 //
1340                 FDBigInteger diff;
1341                 int cmpResult;
1342                 boolean overvalue;
1343                 if ((cmpResult = bigB.cmp(bigD)) > 0) {
1344                     overvalue = true; // our candidate is too big.
1345                     diff = bigB.leftInplaceSub(bigD); // bigB is not user further - reuse
1346                     if ((bigIntNBits == 1) && (bigIntExp > -DoubleConsts.EXP_BIAS + 1)) {
1347                         // candidate is a normalized exact power of 2 and
1348                         // is too big (larger than Double.MIN_NORMAL). We will be subtracting.
1349                         // For our purposes, ulp is the ulp of the
1350                         // next smaller range.
1351                         Ulp2 -= 1;
1352                         if (Ulp2 < 0) {
1353                             // rats. Cannot de-scale ulp this far.
1354                             // must scale diff in other direction.
1355                             Ulp2 = 0;
1356                             diff = diff.leftShift(1);
1357                         }
1358                     }
1359                 } else if (cmpResult < 0) {
1360                     overvalue = false; // our candidate is too small.
1361                     diff = bigD.rightInplaceSub(bigB); // bigB is not user further - reuse
1362                 } else {
1363                     // the candidate is exactly right!
1364                     // this happens with surprising frequency
1365                     break correctionLoop;
1366                 }
1367                 cmpResult = diff.cmpPow52(B5, Ulp2);
1368                 if ((cmpResult) < 0) {
1369                     // difference is small.
1370                     // this is close enough
1371                     break correctionLoop;
1372                 } else if (cmpResult == 0) {
1373                     // difference is exactly half an ULP
1374                     // round to some other value maybe, then finish
1375                     if ((ieeeBits & 1) != 0) { // half ties to even
1376                         ieeeBits += overvalue ? -1 : 1; // nextDown or nextUp
1377                     }
1378                     break correctionLoop;
1379                 } else {
1380                     // difference is non-trivial.
1381                     // could scale addend by ratio of difference to
1382                     // halfUlp here, if we bothered to compute that difference.
1383                     // Most of the time ( I hope ) it is about 1 anyway.
1384                     ieeeBits += overvalue ? -1 : 1; // nextDown or nextUp
1385                     if (ieeeBits == 0 || ieeeBits == DoubleConsts.EXP_BIT_MASK) { // 0.0 or Double.POSITIVE_INFINITY
1386                         break correctionLoop; // oops. Fell off end of range.
1387                     }
1388                     continue; // try again.
1389                 }
1390 
1391             }
1392             if (isNegative) {
1393                 ieeeBits |= DoubleConsts.SIGN_BIT_MASK;
1394             }
1395             return Double.longBitsToDouble(ieeeBits);
1396         }
1397 
1398         /**
1399          * Takes a FloatingDecimal, which we presumably just scanned in,
1400          * and finds out what its value is, as a float.
1401          * This is distinct from doubleValue() to avoid the extremely
1402          * unlikely case of a double rounding error, wherein the conversion
1403          * to double has one rounding error, and the conversion of that double
1404          * to a float has another rounding error, IN THE WRONG DIRECTION,
1405          * ( because of the preference to a zero low-order bit ).
1406          */
1407         @Override
1408         public float floatValue() {
1409             int kDigits = Math.min(nDigits, SINGLE_MAX_DECIMAL_DIGITS + 1);
1410             //
1411             // convert the lead kDigits to an integer.
1412             //
1413             int iValue = (int) digits[0] - (int) '0';
1414             for (int i = 1; i < kDigits; i++) {
1415                 iValue = iValue * 10 + (int) digits[i] - (int) '0';
1416             }
1417             float fValue = (float) iValue;
1418             int exp = decExponent - kDigits;
1419             //
1420             // iValue now contains an integer with the value of
1421             // the first kDigits digits of the number.
1422             // fValue contains the (float) of the same.
1423             //
1424 
1425             if (nDigits <= SINGLE_MAX_DECIMAL_DIGITS) {
1426                 //
1427                 // possibly an easy case.
1428                 // We know that the digits can be represented
1429                 // exactly. And if the exponent isn't too outrageous,
1430                 // the whole thing can be done with one operation,
1431                 // thus one rounding error.
1432                 // Note that all our constructors trim all leading and
1433                 // trailing zeros, so simple values (including zero)
1434                 // will always end up here.
1435                 //
1436                 if (exp == 0 || fValue == 0.0f) {
1437                     return (isNegative) ? -fValue : fValue; // small floating integer
1438                 } else if (exp >= 0) {
1439                     if (exp <= SINGLE_MAX_SMALL_TEN) {
1440                         //
1441                         // Can get the answer with one operation,
1442                         // thus one roundoff.
1443                         //
1444                         fValue *= SINGLE_SMALL_10_POW[exp];
1445                         return (isNegative) ? -fValue : fValue;
1446                     }
1447                     int slop = SINGLE_MAX_DECIMAL_DIGITS - kDigits;
1448                     if (exp <= SINGLE_MAX_SMALL_TEN + slop) {
1449                         //
1450                         // We can multiply fValue by 10^(slop)
1451                         // and it is still "small" and exact.
1452                         // Then we can multiply by 10^(exp-slop)
1453                         // with one rounding.
1454                         //
1455                         fValue *= SINGLE_SMALL_10_POW[slop];
1456                         fValue *= SINGLE_SMALL_10_POW[exp - slop];
1457                         return (isNegative) ? -fValue : fValue;
1458                     }
1459                     //
1460                     // Else we have a hard case with a positive exp.
1461                     //
1462                 } else {
1463                     if (exp >= -SINGLE_MAX_SMALL_TEN) {
1464                         //
1465                         // Can get the answer in one division.
1466                         //
1467                         fValue /= SINGLE_SMALL_10_POW[-exp];
1468                         return (isNegative) ? -fValue : fValue;
1469                     }
1470                     //
1471                     // Else we have a hard case with a negative exp.
1472                     //
1473                 }
1474             } else if ((decExponent >= nDigits) && (nDigits + decExponent <= MAX_DECIMAL_DIGITS)) {
1475                 //
1476                 // In double-precision, this is an exact floating integer.
1477                 // So we can compute to double, then shorten to float
1478                 // with one round, and get the right answer.
1479                 //
1480                 // First, finish accumulating digits.
1481                 // Then convert that integer to a double, multiply
1482                 // by the appropriate power of ten, and convert to float.
1483                 //
1484                 long lValue = (long) iValue;
1485                 for (int i = kDigits; i < nDigits; i++) {
1486                     lValue = lValue * 10L + (long) ((int) digits[i] - (int) '0');
1487                 }
1488                 double dValue = (double) lValue;
1489                 exp = decExponent - nDigits;
1490                 dValue *= SMALL_10_POW[exp];
1491                 fValue = (float) dValue;
1492                 return (isNegative) ? -fValue : fValue;
1493 
1494             }
1495             //
1496             // Harder cases:
1497             // The sum of digits plus exponent is greater than
1498             // what we think we can do with one error.
1499             //
1500             // Start by approximating the right answer by,
1501             // naively, scaling by powers of 10.
1502             // Scaling uses doubles to avoid overflow/underflow.
1503             //
1504             double dValue = fValue;
1505             if (exp > 0) {
1506                 if (decExponent > SINGLE_MAX_DECIMAL_EXPONENT + 1) {
1507                     //
1508                     // Lets face it. This is going to be
1509                     // Infinity. Cut to the chase.
1510                     //
1511                     return (isNegative) ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
1512                 }
1513                 if ((exp & 15) != 0) {
1514                     dValue *= SMALL_10_POW[exp & 15];
1515                 }
1516                 if ((exp >>= 4) != 0) {
1517                     int j;
1518                     for (j = 0; exp > 0; j++, exp >>= 1) {
1519                         if ((exp & 1) != 0) {
1520                             dValue *= BIG_10_POW[j];
1521                         }
1522                     }
1523                 }
1524             } else if (exp < 0) {
1525                 exp = -exp;
1526                 if (decExponent < SINGLE_MIN_DECIMAL_EXPONENT - 1) {
1527                     //
1528                     // Lets face it. This is going to be
1529                     // zero. Cut to the chase.
1530                     //
1531                     return (isNegative) ? -0.0f : 0.0f;
1532                 }
1533                 if ((exp & 15) != 0) {
1534                     dValue /= SMALL_10_POW[exp & 15];
1535                 }
1536                 if ((exp >>= 4) != 0) {
1537                     int j;
1538                     for (j = 0; exp > 0; j++, exp >>= 1) {
1539                         if ((exp & 1) != 0) {
1540                             dValue *= TINY_10_POW[j];
1541                         }
1542                     }
1543                 }
1544             }
1545             fValue = Math.max(Float.MIN_VALUE, Math.min(Float.MAX_VALUE, (float) dValue));
1546 
1547             //
1548             // fValue is now approximately the result.
1549             // The hard part is adjusting it, by comparison
1550             // with FDBigInteger arithmetic.
1551             // Formulate the EXACT big-number result as
1552             // bigD0 * 10^exp
1553             //
1554             if (nDigits > SINGLE_MAX_NDIGITS) {
1555                 nDigits = SINGLE_MAX_NDIGITS + 1;
1556                 digits[SINGLE_MAX_NDIGITS] = '1';
1557             }
1558             FDBigInteger bigD0 = new FDBigInteger(iValue, digits, kDigits, nDigits);
1559             exp = decExponent - nDigits;
1560 
1561             int ieeeBits = Float.floatToRawIntBits(fValue); // IEEE-754 bits of float candidate
1562             final int B5 = Math.max(0, -exp); // powers of 5 in bigB, value is not modified inside correctionLoop
1563             final int D5 = Math.max(0, exp); // powers of 5 in bigD, value is not modified inside correctionLoop
1564             bigD0 = bigD0.multByPow52(D5, 0);
1565             bigD0.makeImmutable();   // prevent bigD0 modification inside correctionLoop
1566             FDBigInteger bigD = null;
1567             int prevD2 = 0;
1568 
1569             correctionLoop:
1570             while (true) {
1571                 // here ieeeBits can't be NaN, Infinity or zero
1572                 int binexp = ieeeBits >>> SINGLE_EXP_SHIFT;
1573                 int bigBbits = ieeeBits & FloatConsts.SIGNIF_BIT_MASK;
1574                 if (binexp > 0) {
1575                     bigBbits |= SINGLE_FRACT_HOB;
1576                 } else { // Normalize denormalized numbers.
1577                     assert bigBbits != 0 : bigBbits; // floatToBigInt(0.0)
1578                     int leadingZeros = Integer.numberOfLeadingZeros(bigBbits);
1579                     int shift = leadingZeros - (31 - SINGLE_EXP_SHIFT);
1580                     bigBbits <<= shift;
1581                     binexp = 1 - shift;
1582                 }
1583                 binexp -= FloatConsts.EXP_BIAS;
1584                 int lowOrderZeros = Integer.numberOfTrailingZeros(bigBbits);
1585                 bigBbits >>>= lowOrderZeros;
1586                 final int bigIntExp = binexp - SINGLE_EXP_SHIFT + lowOrderZeros;
1587                 final int bigIntNBits = SINGLE_EXP_SHIFT + 1 - lowOrderZeros;
1588 
1589                 //
1590                 // Scale bigD, bigB appropriately for
1591                 // big-integer operations.
1592                 // Naively, we multiply by powers of ten
1593                 // and powers of two. What we actually do
1594                 // is keep track of the powers of 5 and
1595                 // powers of 2 we would use, then factor out
1596                 // common divisors before doing the work.
1597                 //
1598                 int B2 = B5; // powers of 2 in bigB
1599                 int D2 = D5; // powers of 2 in bigD
1600                 int Ulp2;   // powers of 2 in halfUlp.
1601                 if (bigIntExp >= 0) {
1602                     B2 += bigIntExp;
1603                 } else {
1604                     D2 -= bigIntExp;
1605                 }
1606                 Ulp2 = B2;
1607                 // shift bigB and bigD left by a number s. t.
1608                 // halfUlp is still an integer.
1609                 int hulpbias;
1610                 if (binexp <= -FloatConsts.EXP_BIAS) {
1611                     // This is going to be a denormalized number
1612                     // (if not actually zero).
1613                     // half an ULP is at 2^-(FloatConsts.EXP_BIAS+SINGLE_EXP_SHIFT+1)
1614                     hulpbias = binexp + lowOrderZeros + FloatConsts.EXP_BIAS;
1615                 } else {
1616                     hulpbias = 1 + lowOrderZeros;
1617                 }
1618                 B2 += hulpbias;
1619                 D2 += hulpbias;
1620                 // if there are common factors of 2, we might just as well
1621                 // factor them out, as they add nothing useful.
1622                 int common2 = Math.min(B2, Math.min(D2, Ulp2));
1623                 B2 -= common2;
1624                 D2 -= common2;
1625                 Ulp2 -= common2;
1626                 // do multiplications by powers of 5 and 2
1627                 FDBigInteger bigB = FDBigInteger.valueOfMulPow52(bigBbits, B5, B2);
1628                 if (bigD == null || prevD2 != D2) {
1629                     bigD = bigD0.leftShift(D2);
1630                     prevD2 = D2;
1631                 }
1632                 //
1633                 // to recap:
1634                 // bigB is the scaled-big-int version of our floating-point
1635                 // candidate.
1636                 // bigD is the scaled-big-int version of the exact value
1637                 // as we understand it.
1638                 // halfUlp is 1/2 an ulp of bigB, except for special cases
1639                 // of exact powers of 2
1640                 //
1641                 // the plan is to compare bigB with bigD, and if the difference
1642                 // is less than halfUlp, then we're satisfied. Otherwise,
1643                 // use the ratio of difference to halfUlp to calculate a fudge
1644                 // factor to add to the floating value, then go 'round again.
1645                 //
1646                 FDBigInteger diff;
1647                 int cmpResult;
1648                 boolean overvalue;
1649                 if ((cmpResult = bigB.cmp(bigD)) > 0) {
1650                     overvalue = true; // our candidate is too big.
1651                     diff = bigB.leftInplaceSub(bigD); // bigB is not user further - reuse
1652                     if ((bigIntNBits == 1) && (bigIntExp > -FloatConsts.EXP_BIAS + 1)) {
1653                         // candidate is a normalized exact power of 2 and
1654                         // is too big (larger than Float.MIN_NORMAL). We will be subtracting.
1655                         // For our purposes, ulp is the ulp of the
1656                         // next smaller range.
1657                         Ulp2 -= 1;
1658                         if (Ulp2 < 0) {
1659                             // rats. Cannot de-scale ulp this far.
1660                             // must scale diff in other direction.
1661                             Ulp2 = 0;
1662                             diff = diff.leftShift(1);
1663                         }
1664                     }
1665                 } else if (cmpResult < 0) {
1666                     overvalue = false; // our candidate is too small.
1667                     diff = bigD.rightInplaceSub(bigB); // bigB is not user further - reuse
1668                 } else {
1669                     // the candidate is exactly right!
1670                     // this happens with surprising frequency
1671                     break correctionLoop;
1672                 }
1673                 cmpResult = diff.cmpPow52(B5, Ulp2);
1674                 if ((cmpResult) < 0) {
1675                     // difference is small.
1676                     // this is close enough
1677                     break correctionLoop;
1678                 } else if (cmpResult == 0) {
1679                     // difference is exactly half an ULP
1680                     // round to some other value maybe, then finish
1681                     if ((ieeeBits & 1) != 0) { // half ties to even
1682                         ieeeBits += overvalue ? -1 : 1; // nextDown or nextUp
1683                     }
1684                     break correctionLoop;
1685                 } else {
1686                     // difference is non-trivial.
1687                     // could scale addend by ratio of difference to
1688                     // halfUlp here, if we bothered to compute that difference.
1689                     // Most of the time ( I hope ) it is about 1 anyway.
1690                     ieeeBits += overvalue ? -1 : 1; // nextDown or nextUp
1691                     if (ieeeBits == 0 || ieeeBits == FloatConsts.EXP_BIT_MASK) { // 0.0 or Float.POSITIVE_INFINITY
1692                         break correctionLoop; // oops. Fell off end of range.
1693                     }
1694                     continue; // try again.
1695                 }
1696 
1697             }
1698             if (isNegative) {
1699                 ieeeBits |= FloatConsts.SIGN_BIT_MASK;
1700             }
1701             return Float.intBitsToFloat(ieeeBits);
1702         }
1703 
1704 
1705         /**
1706          * All the positive powers of 10 that can be
1707          * represented exactly in double/float.
1708          */
1709         private static final double[] SMALL_10_POW = {
1710             1.0e0,
1711             1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5,
1712             1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10,
1713             1.0e11, 1.0e12, 1.0e13, 1.0e14, 1.0e15,
1714             1.0e16, 1.0e17, 1.0e18, 1.0e19, 1.0e20,
1715             1.0e21, 1.0e22
1716         };
1717 
1718         private static final float[] SINGLE_SMALL_10_POW = {
1719             1.0e0f,
1720             1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,
1721             1.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f
1722         };
1723 
1724         private static final double[] BIG_10_POW = {
1725             1e16, 1e32, 1e64, 1e128, 1e256 };
1726         private static final double[] TINY_10_POW = {
1727             1e-16, 1e-32, 1e-64, 1e-128, 1e-256 };
1728 
1729         private static final int MAX_SMALL_TEN = SMALL_10_POW.length-1;
1730         private static final int SINGLE_MAX_SMALL_TEN = SINGLE_SMALL_10_POW.length-1;
1731 
1732     }
1733 
1734     /**
1735      * Returns a <code>BinaryToASCIIConverter</code> for a <code>double</code>.
1736      * The returned object is a <code>ThreadLocal</code> variable of this class.
1737      *
1738      * @param d The double precision value to convert.
1739      * @return The converter.
1740      */
1741     public static BinaryToASCIIConverter getBinaryToASCIIConverter(double d) {
1742         return getBinaryToASCIIConverter(d, true);
1743     }
1744 
1745     /**
1746      * Returns a <code>BinaryToASCIIConverter</code> for a <code>double</code>.
1747      * The returned object is a <code>ThreadLocal</code> variable of this class.
1748      *
1749      * @param d The double precision value to convert.
1750      * @param isCompatibleFormat
1751      * @return The converter.
1752      */
1753     static BinaryToASCIIConverter getBinaryToASCIIConverter(double d, boolean isCompatibleFormat) {
1754         long dBits = Double.doubleToRawLongBits(d);
1755         boolean isNegative = (dBits&DoubleConsts.SIGN_BIT_MASK) != 0; // discover sign
1756         long fractBits = dBits & DoubleConsts.SIGNIF_BIT_MASK;
1757         int  binExp = (int)( (dBits&DoubleConsts.EXP_BIT_MASK) >> EXP_SHIFT );
1758         // Discover obvious special cases of NaN and Infinity.
1759         if ( binExp == (int)(DoubleConsts.EXP_BIT_MASK>>EXP_SHIFT) ) {
1760             if ( fractBits == 0L ){
1761                 return isNegative ? B2AC_NEGATIVE_INFINITY : B2AC_POSITIVE_INFINITY;
1762             } else {
1763                 return B2AC_NOT_A_NUMBER;
1764             }
1765         }
1766         // Finish unpacking
1767         // Normalize denormalized numbers.
1768         // Insert assumed high-order bit for normalized numbers.
1769         // Subtract exponent bias.
1770         int  nSignificantBits;
1771         if ( binExp == 0 ){
1772             if ( fractBits == 0L ){
1773                 // not a denorm, just a 0!
1774                 return isNegative ? B2AC_NEGATIVE_ZERO : B2AC_POSITIVE_ZERO;
1775             }
1776             int leadingZeros = Long.numberOfLeadingZeros(fractBits);
1777             int shift = leadingZeros-(63-EXP_SHIFT);
1778             fractBits <<= shift;
1779             binExp = 1 - shift;
1780             nSignificantBits =  64-leadingZeros; // recall binExp is  - shift count.
1781         } else {
1782             fractBits |= FRACT_HOB;
1783             nSignificantBits = EXP_SHIFT+1;
1784         }
1785         binExp -= DoubleConsts.EXP_BIAS;
1786         BinaryToASCIIBuffer buf = getBinaryToASCIIBuffer();
1787         buf.setSign(isNegative);
1788         // call the routine that actually does all the hard work.
1789         buf.dtoa(binExp, fractBits, nSignificantBits, isCompatibleFormat);
1790         return buf;
1791     }
1792 
1793     private static BinaryToASCIIConverter getBinaryToASCIIConverter(float f) {
1794         int fBits = Float.floatToRawIntBits( f );
1795         boolean isNegative = (fBits&FloatConsts.SIGN_BIT_MASK) != 0;
1796         int fractBits = fBits&FloatConsts.SIGNIF_BIT_MASK;
1797         int binExp = (fBits&FloatConsts.EXP_BIT_MASK) >> SINGLE_EXP_SHIFT;
1798         // Discover obvious special cases of NaN and Infinity.
1799         if ( binExp == (FloatConsts.EXP_BIT_MASK>>SINGLE_EXP_SHIFT) ) {
1800             if ( fractBits == 0L ){
1801                 return isNegative ? B2AC_NEGATIVE_INFINITY : B2AC_POSITIVE_INFINITY;
1802             } else {
1803                 return B2AC_NOT_A_NUMBER;
1804             }
1805         }
1806         // Finish unpacking
1807         // Normalize denormalized numbers.
1808         // Insert assumed high-order bit for normalized numbers.
1809         // Subtract exponent bias.
1810         int  nSignificantBits;
1811         if ( binExp == 0 ){
1812             if ( fractBits == 0 ){
1813                 // not a denorm, just a 0!
1814                 return isNegative ? B2AC_NEGATIVE_ZERO : B2AC_POSITIVE_ZERO;
1815             }
1816             int leadingZeros = Integer.numberOfLeadingZeros(fractBits);
1817             int shift = leadingZeros-(31-SINGLE_EXP_SHIFT);
1818             fractBits <<= shift;
1819             binExp = 1 - shift;
1820             nSignificantBits =  32 - leadingZeros; // recall binExp is  - shift count.
1821         } else {
1822             fractBits |= SINGLE_FRACT_HOB;
1823             nSignificantBits = SINGLE_EXP_SHIFT+1;
1824         }
1825         binExp -= FloatConsts.EXP_BIAS;
1826         BinaryToASCIIBuffer buf = getBinaryToASCIIBuffer();
1827         buf.setSign(isNegative);
1828         // call the routine that actually does all the hard work.
1829         buf.dtoa(binExp, ((long)fractBits)<<(EXP_SHIFT-SINGLE_EXP_SHIFT), nSignificantBits, true);
1830         return buf;
1831     }
1832 
1833     @SuppressWarnings("fallthrough")
1834     static ASCIIToBinaryConverter readJavaFormatString( String in ) throws NumberFormatException {
1835         boolean isNegative = false;
1836         boolean signSeen   = false;
1837         int     decExp;
1838         char    c;
1839 
1840     parseNumber:
1841         try{
1842             in = in.trim(); // don't fool around with white space.
1843                             // throws NullPointerException if null
1844             int len = in.length();
1845             if ( len == 0 ) {
1846                 throw new NumberFormatException("empty String");
1847             }
1848             int i = 0;
1849             switch (in.charAt(i)){
1850             case '-':
1851                 isNegative = true;
1852                 //FALLTHROUGH
1853             case '+':
1854                 i++;
1855                 signSeen = true;
1856             }
1857             c = in.charAt(i);
1858             if(c == 'N') { // Check for NaN
1859                 if((len-i)==NAN_LENGTH && in.indexOf(NAN_REP,i)==i) {
1860                     return A2BC_NOT_A_NUMBER;
1861                 }
1862                 // something went wrong, throw exception
1863                 break parseNumber;
1864             } else if(c == 'I') { // Check for Infinity strings
1865                 if((len-i)==INFINITY_LENGTH && in.indexOf(INFINITY_REP,i)==i) {
1866                     return isNegative? A2BC_NEGATIVE_INFINITY : A2BC_POSITIVE_INFINITY;
1867                 }
1868                 // something went wrong, throw exception
1869                 break parseNumber;
1870             } else if (c == '0')  { // check for hexadecimal floating-point number
1871                 if (len > i+1 ) {
1872                     char ch = in.charAt(i+1);
1873                     if (ch == 'x' || ch == 'X' ) { // possible hex string
1874                         return parseHexString(in);
1875                     }
1876                 }
1877             }  // look for and process decimal floating-point string
1878 
1879             char[] digits = new char[ len ];
1880             boolean decSeen = false;
1881             int nDigits = 0;
1882             int decPt = 0;
1883             int nLeadZero = 0;
1884             int nTrailZero = 0;
1885 
1886         skipLeadingZerosLoop:
1887             while (i < len) {
1888                 c = in.charAt(i);
1889                 if (c == '0') {
1890                     nLeadZero++;
1891                 } else if (c == '.') {
1892                     if (decSeen) {
1893                         // already saw one ., this is the 2nd.
1894                         throw new NumberFormatException("multiple points");
1895                     }
1896                     decPt = i;
1897                     if (signSeen) {
1898                         decPt -= 1;
1899                     }
1900                     decSeen = true;
1901                 } else {
1902                     break skipLeadingZerosLoop;
1903                 }
1904                 i++;
1905             }
1906         digitLoop:
1907             while (i < len) {
1908                 c = in.charAt(i);
1909                 if (c >= '1' && c <= '9') {
1910                     digits[nDigits++] = c;
1911                     nTrailZero = 0;
1912                 } else if (c == '0') {
1913                     digits[nDigits++] = c;
1914                     nTrailZero++;
1915                 } else if (c == '.') {
1916                     if (decSeen) {
1917                         // already saw one ., this is the 2nd.
1918                         throw new NumberFormatException("multiple points");
1919                     }
1920                     decPt = i;
1921                     if (signSeen) {
1922                         decPt -= 1;
1923                     }
1924                     decSeen = true;
1925                 } else {
1926                     break digitLoop;
1927                 }
1928                 i++;
1929             }
1930             nDigits -=nTrailZero;
1931             //
1932             // At this point, we've scanned all the digits and decimal
1933             // point we're going to see. Trim off leading and trailing
1934             // zeros, which will just confuse us later, and adjust
1935             // our initial decimal exponent accordingly.
1936             // To review:
1937             // we have seen i total characters.
1938             // nLeadZero of them were zeros before any other digits.
1939             // nTrailZero of them were zeros after any other digits.
1940             // if ( decSeen ), then a . was seen after decPt characters
1941             // ( including leading zeros which have been discarded )
1942             // nDigits characters were neither lead nor trailing
1943             // zeros, nor point
1944             //
1945             //
1946             // special hack: if we saw no non-zero digits, then the
1947             // answer is zero!
1948             // Unfortunately, we feel honor-bound to keep parsing!
1949             //
1950             boolean isZero = (nDigits == 0);
1951             if ( isZero &&  nLeadZero == 0 ){
1952                 // we saw NO DIGITS AT ALL,
1953                 // not even a crummy 0!
1954                 // this is not allowed.
1955                 break parseNumber; // go throw exception
1956             }
1957             //
1958             // Our initial exponent is decPt, adjusted by the number of
1959             // discarded zeros. Or, if there was no decPt,
1960             // then its just nDigits adjusted by discarded trailing zeros.
1961             //
1962             if ( decSeen ){
1963                 decExp = decPt - nLeadZero;
1964             } else {
1965                 decExp = nDigits + nTrailZero;
1966             }
1967 
1968             //
1969             // Look for 'e' or 'E' and an optionally signed integer.
1970             //
1971             if ( (i < len) &&  (((c = in.charAt(i) )=='e') || (c == 'E') ) ){
1972                 int expSign = 1;
1973                 int expVal  = 0;
1974                 int reallyBig = Integer.MAX_VALUE / 10;
1975                 boolean expOverflow = false;
1976                 switch( in.charAt(++i) ){
1977                 case '-':
1978                     expSign = -1;
1979                     //FALLTHROUGH
1980                 case '+':
1981                     i++;
1982                 }
1983                 int expAt = i;
1984             expLoop:
1985                 while ( i < len  ){
1986                     if ( expVal >= reallyBig ){
1987                         // the next character will cause integer
1988                         // overflow.
1989                         expOverflow = true;
1990                     }
1991                     c = in.charAt(i++);
1992                     if(c>='0' && c<='9') {
1993                         expVal = expVal*10 + ( (int)c - (int)'0' );
1994                     } else {
1995                         i--;           // back up.
1996                         break expLoop; // stop parsing exponent.
1997                     }
1998                 }
1999                 int expLimit = BIG_DECIMAL_EXPONENT + nDigits + nTrailZero;
2000                 if (expOverflow || (expVal > expLimit)) {
2001                     // There is still a chance that the exponent will be safe to
2002                     // use: if it would eventually decrease due to a negative
2003                     // decExp, and that number is below the limit.  We check for
2004                     // that here.
2005                     if (!expOverflow && (expSign == 1 && decExp < 0)
2006                             && (expVal + decExp) < expLimit) {
2007                         // Cannot overflow: adding a positive and negative number.
2008                         decExp += expVal;
2009                     } else {
2010                         //
2011                         // The intent here is to end up with
2012                         // infinity or zero, as appropriate.
2013                         // The reason for yielding such a small decExponent,
2014                         // rather than something intuitive such as
2015                         // expSign*Integer.MAX_VALUE, is that this value
2016                         // is subject to further manipulation in
2017                         // doubleValue() and floatValue(), and I don't want
2018                         // it to be able to cause overflow there!
2019                         // (The only way we can get into trouble here is for
2020                         // really outrageous nDigits+nTrailZero, such as 2
2021                         // billion.)
2022                         //
2023                         decExp = expSign * expLimit;
2024                     }
2025                 } else {
2026                     // this should not overflow, since we tested
2027                     // for expVal > (MAX+N), where N >= abs(decExp)
2028                     decExp = decExp + expSign*expVal;
2029                 }
2030 
2031                 // if we saw something not a digit ( or end of string )
2032                 // after the [Ee][+-], without seeing any digits at all
2033                 // this is certainly an error. If we saw some digits,
2034                 // but then some trailing garbage, that might be ok.
2035                 // so we just fall through in that case.
2036                 // HUMBUG
2037                 if ( i == expAt ) {
2038                     break parseNumber; // certainly bad
2039                 }
2040             }
2041             //
2042             // We parsed everything we could.
2043             // If there are leftovers, then this is not good input!
2044             //
2045             if ( i < len &&
2046                 ((i != len - 1) ||
2047                 (in.charAt(i) != 'f' &&
2048                  in.charAt(i) != 'F' &&
2049                  in.charAt(i) != 'd' &&
2050                  in.charAt(i) != 'D'))) {
2051                 break parseNumber; // go throw exception
2052             }
2053             if(isZero) {
2054                 return isNegative ? A2BC_NEGATIVE_ZERO : A2BC_POSITIVE_ZERO;
2055             }
2056             return new ASCIIToBinaryBuffer(isNegative, decExp, digits, nDigits);
2057         } catch ( StringIndexOutOfBoundsException e ){ }
2058         throw new NumberFormatException("For input string: \"" + in + "\"");
2059     }
2060 
2061     private static class HexFloatPattern {
2062         /**
2063          * Grammar is compatible with hexadecimal floating-point constants
2064          * described in section 6.4.4.2 of the C99 specification.
2065          */
2066         private static final Pattern VALUE = Pattern.compile(
2067                    //1           234                   56                7                   8      9
2068                     "([-+])?0[xX](((\\p{XDigit}+)\\.?)|((\\p{XDigit}*)\\.(\\p{XDigit}+)))[pP]([-+])?(\\p{Digit}+)[fFdD]?"
2069                     );
2070     }
2071 
2072     /**
2073      * Converts string s to a suitable floating decimal; uses the
2074      * double constructor and sets the roundDir variable appropriately
2075      * in case the value is later converted to a float.
2076      *
2077      * @param s The <code>String</code> to parse.
2078      */
2079    static ASCIIToBinaryConverter parseHexString(String s) {
2080             // Verify string is a member of the hexadecimal floating-point
2081             // string language.
2082             Matcher m = HexFloatPattern.VALUE.matcher(s);
2083             boolean validInput = m.matches();
2084             if (!validInput) {
2085                 // Input does not match pattern
2086                 throw new NumberFormatException("For input string: \"" + s + "\"");
2087             } else { // validInput
2088                 //
2089                 // We must isolate the sign, significand, and exponent
2090                 // fields.  The sign value is straightforward.  Since
2091                 // floating-point numbers are stored with a normalized
2092                 // representation, the significand and exponent are
2093                 // interrelated.
2094                 //
2095                 // After extracting the sign, we normalized the
2096                 // significand as a hexadecimal value, calculating an
2097                 // exponent adjust for any shifts made during
2098                 // normalization.  If the significand is zero, the
2099                 // exponent doesn't need to be examined since the output
2100                 // will be zero.
2101                 //
2102                 // Next the exponent in the input string is extracted.
2103                 // Afterwards, the significand is normalized as a *binary*
2104                 // value and the input value's normalized exponent can be
2105                 // computed.  The significand bits are copied into a
2106                 // double significand; if the string has more logical bits
2107                 // than can fit in a double, the extra bits affect the
2108                 // round and sticky bits which are used to round the final
2109                 // value.
2110                 //
2111                 //  Extract significand sign
2112                 String group1 = m.group(1);
2113                 boolean isNegative = ((group1 != null) && group1.equals("-"));
2114 
2115                 //  Extract Significand magnitude
2116                 //
2117                 // Based on the form of the significand, calculate how the
2118                 // binary exponent needs to be adjusted to create a
2119                 // normalized//hexadecimal* floating-point number; that
2120                 // is, a number where there is one nonzero hex digit to
2121                 // the left of the (hexa)decimal point.  Since we are
2122                 // adjusting a binary, not hexadecimal exponent, the
2123                 // exponent is adjusted by a multiple of 4.
2124                 //
2125                 // There are a number of significand scenarios to consider;
2126                 // letters are used in indicate nonzero digits:
2127                 //
2128                 // 1. 000xxxx       =>      x.xxx   normalized
2129                 //    increase exponent by (number of x's - 1)*4
2130                 //
2131                 // 2. 000xxx.yyyy =>        x.xxyyyy        normalized
2132                 //    increase exponent by (number of x's - 1)*4
2133                 //
2134                 // 3. .000yyy  =>   y.yy    normalized
2135                 //    decrease exponent by (number of zeros + 1)*4
2136                 //
2137                 // 4. 000.00000yyy => y.yy normalized
2138                 //    decrease exponent by (number of zeros to right of point + 1)*4
2139                 //
2140                 // If the significand is exactly zero, return a properly
2141                 // signed zero.
2142                 //
2143 
2144                 String significandString;
2145                 int signifLength;
2146                 int exponentAdjust;
2147                 {
2148                     int leftDigits = 0; // number of meaningful digits to
2149                     // left of "decimal" point
2150                     // (leading zeros stripped)
2151                     int rightDigits = 0; // number of digits to right of
2152                     // "decimal" point; leading zeros
2153                     // must always be accounted for
2154                     //
2155                     // The significand is made up of either
2156                     //
2157                     // 1. group 4 entirely (integer portion only)
2158                     //
2159                     // OR
2160                     //
2161                     // 2. the fractional portion from group 7 plus any
2162                     // (optional) integer portions from group 6.
2163                     //
2164                     String group4;
2165                     if ((group4 = m.group(4)) != null) {  // Integer-only significand
2166                         // Leading zeros never matter on the integer portion
2167                         significandString = stripLeadingZeros(group4);
2168                         leftDigits = significandString.length();
2169                     } else {
2170                         // Group 6 is the optional integer; leading zeros
2171                         // never matter on the integer portion
2172                         String group6 = stripLeadingZeros(m.group(6));
2173                         leftDigits = group6.length();
2174 
2175                         // fraction
2176                         String group7 = m.group(7);
2177                         rightDigits = group7.length();
2178 
2179                         // Turn "integer.fraction" into "integer"+"fraction"
2180                         significandString =
2181                                 ((group6 == null) ? "" : group6) + // is the null
2182                                         // check necessary?
2183                                         group7;
2184                     }
2185 
2186                     significandString = stripLeadingZeros(significandString);
2187                     signifLength = significandString.length();
2188 
2189                     //
2190                     // Adjust exponent as described above
2191                     //
2192                     if (leftDigits >= 1) {  // Cases 1 and 2
2193                         exponentAdjust = 4 * (leftDigits - 1);
2194                     } else {                // Cases 3 and 4
2195                         exponentAdjust = -4 * (rightDigits - signifLength + 1);
2196                     }
2197 
2198                     // If the significand is zero, the exponent doesn't
2199                     // matter; return a properly signed zero.
2200 
2201                     if (signifLength == 0) { // Only zeros in input
2202                         return isNegative ? A2BC_NEGATIVE_ZERO : A2BC_POSITIVE_ZERO;
2203                     }
2204                 }
2205 
2206                 //  Extract Exponent
2207                 //
2208                 // Use an int to read in the exponent value; this should
2209                 // provide more than sufficient range for non-contrived
2210                 // inputs.  If reading the exponent in as an int does
2211                 // overflow, examine the sign of the exponent and
2212                 // significand to determine what to do.
2213                 //
2214                 String group8 = m.group(8);
2215                 boolean positiveExponent = (group8 == null) || group8.equals("+");
2216                 long unsignedRawExponent;
2217                 try {
2218                     unsignedRawExponent = Integer.parseInt(m.group(9));
2219                 }
2220                 catch (NumberFormatException e) {
2221                     // At this point, we know the exponent is
2222                     // syntactically well-formed as a sequence of
2223                     // digits.  Therefore, if an NumberFormatException
2224                     // is thrown, it must be due to overflowing int's
2225                     // range.  Also, at this point, we have already
2226                     // checked for a zero significand.  Thus the signs
2227                     // of the exponent and significand determine the
2228                     // final result:
2229                     //
2230                     //                      significand
2231                     //                      +               -
2232                     // exponent     +       +infinity       -infinity
2233                     //              -       +0.0            -0.0
2234                     return isNegative ?
2235                               (positiveExponent ? A2BC_NEGATIVE_INFINITY : A2BC_NEGATIVE_ZERO)
2236                             : (positiveExponent ? A2BC_POSITIVE_INFINITY : A2BC_POSITIVE_ZERO);
2237 
2238                 }
2239 
2240                 long rawExponent =
2241                         (positiveExponent ? 1L : -1L) * // exponent sign
2242                                 unsignedRawExponent;            // exponent magnitude
2243 
2244                 // Calculate partially adjusted exponent
2245                 long exponent = rawExponent + exponentAdjust;
2246 
2247                 // Starting copying non-zero bits into proper position in
2248                 // a long; copy explicit bit too; this will be masked
2249                 // later for normal values.
2250 
2251                 boolean round = false;
2252                 boolean sticky = false;
2253                 int nextShift;
2254                 long significand = 0L;
2255                 // First iteration is different, since we only copy
2256                 // from the leading significand bit; one more exponent
2257                 // adjust will be needed...
2258 
2259                 // IMPORTANT: make leadingDigit a long to avoid
2260                 // surprising shift semantics!
2261                 long leadingDigit = getHexDigit(significandString, 0);
2262 
2263                 //
2264                 // Left shift the leading digit (53 - (bit position of
2265                 // leading 1 in digit)); this sets the top bit of the
2266                 // significand to 1.  The nextShift value is adjusted
2267                 // to take into account the number of bit positions of
2268                 // the leadingDigit actually used.  Finally, the
2269                 // exponent is adjusted to normalize the significand
2270                 // as a binary value, not just a hex value.
2271                 //
2272                 if (leadingDigit == 1) {
2273                     significand |= leadingDigit << 52;
2274                     nextShift = 52 - 4;
2275                     // exponent += 0
2276                 } else if (leadingDigit <= 3) { // [2, 3]
2277                     significand |= leadingDigit << 51;
2278                     nextShift = 52 - 5;
2279                     exponent += 1;
2280                 } else if (leadingDigit <= 7) { // [4, 7]
2281                     significand |= leadingDigit << 50;
2282                     nextShift = 52 - 6;
2283                     exponent += 2;
2284                 } else if (leadingDigit <= 15) { // [8, f]
2285                     significand |= leadingDigit << 49;
2286                     nextShift = 52 - 7;
2287                     exponent += 3;
2288                 } else {
2289                     throw new AssertionError("Result from digit conversion too large!");
2290                 }
2291                 // The preceding if-else could be replaced by a single
2292                 // code block based on the high-order bit set in
2293                 // leadingDigit.  Given leadingOnePosition,
2294 
2295                 // significand |= leadingDigit << (SIGNIFICAND_WIDTH - leadingOnePosition);
2296                 // nextShift = 52 - (3 + leadingOnePosition);
2297                 // exponent += (leadingOnePosition-1);
2298 
2299                 //
2300                 // Now the exponent variable is equal to the normalized
2301                 // binary exponent.  Code below will make representation
2302                 // adjustments if the exponent is incremented after
2303                 // rounding (includes overflows to infinity) or if the
2304                 // result is subnormal.
2305                 //
2306 
2307                 // Copy digit into significand until the significand can't
2308                 // hold another full hex digit or there are no more input
2309                 // hex digits.
2310                 int i = 0;
2311                 for (i = 1;
2312                      i < signifLength && nextShift >= 0;
2313                      i++) {
2314                     long currentDigit = getHexDigit(significandString, i);
2315                     significand |= (currentDigit << nextShift);
2316                     nextShift -= 4;
2317                 }
2318 
2319                 // After the above loop, the bulk of the string is copied.
2320                 // Now, we must copy any partial hex digits into the
2321                 // significand AND compute the round bit and start computing
2322                 // sticky bit.
2323 
2324                 if (i < signifLength) { // at least one hex input digit exists
2325                     long currentDigit = getHexDigit(significandString, i);
2326 
2327                     // from nextShift, figure out how many bits need
2328                     // to be copied, if any
2329                     switch (nextShift) { // must be negative
2330                         case -1:
2331                             // three bits need to be copied in; can
2332                             // set round bit
2333                             significand |= ((currentDigit & 0xEL) >> 1);
2334                             round = (currentDigit & 0x1L) != 0L;
2335                             break;
2336 
2337                         case -2:
2338                             // two bits need to be copied in; can
2339                             // set round and start sticky
2340                             significand |= ((currentDigit & 0xCL) >> 2);
2341                             round = (currentDigit & 0x2L) != 0L;
2342                             sticky = (currentDigit & 0x1L) != 0;
2343                             break;
2344 
2345                         case -3:
2346                             // one bit needs to be copied in
2347                             significand |= ((currentDigit & 0x8L) >> 3);
2348                             // Now set round and start sticky, if possible
2349                             round = (currentDigit & 0x4L) != 0L;
2350                             sticky = (currentDigit & 0x3L) != 0;
2351                             break;
2352 
2353                         case -4:
2354                             // all bits copied into significand; set
2355                             // round and start sticky
2356                             round = ((currentDigit & 0x8L) != 0);  // is top bit set?
2357                             // nonzeros in three low order bits?
2358                             sticky = (currentDigit & 0x7L) != 0;
2359                             break;
2360 
2361                         default:
2362                             throw new AssertionError("Unexpected shift distance remainder.");
2363                             // break;
2364                     }
2365 
2366                     // Round is set; sticky might be set.
2367 
2368                     // For the sticky bit, it suffices to check the
2369                     // current digit and test for any nonzero digits in
2370                     // the remaining unprocessed input.
2371                     i++;
2372                     while (i < signifLength && !sticky) {
2373                         currentDigit = getHexDigit(significandString, i);
2374                         sticky = sticky || (currentDigit != 0);
2375                         i++;
2376                     }
2377 
2378                 }
2379                 // else all of string was seen, round and sticky are
2380                 // correct as false.
2381 
2382                 // Float calculations
2383                 int floatBits = isNegative ? FloatConsts.SIGN_BIT_MASK : 0;
2384                 if (exponent >= Float.MIN_EXPONENT) {
2385                     if (exponent > Float.MAX_EXPONENT) {
2386                         // Float.POSITIVE_INFINITY
2387                         floatBits |= FloatConsts.EXP_BIT_MASK;
2388                     } else {
2389                         int threshShift = DoubleConsts.SIGNIFICAND_WIDTH - FloatConsts.SIGNIFICAND_WIDTH - 1;
2390                         boolean floatSticky = (significand & ((1L << threshShift) - 1)) != 0 || round || sticky;
2391                         int iValue = (int) (significand >>> threshShift);
2392                         if ((iValue & 3) != 1 || floatSticky) {
2393                             iValue++;
2394                         }
2395                         floatBits |= (((((int) exponent) + (FloatConsts.EXP_BIAS - 1))) << SINGLE_EXP_SHIFT) + (iValue >> 1);
2396                     }
2397                 } else {
2398                     if (exponent < FloatConsts.MIN_SUB_EXPONENT - 1) {
2399                         // 0
2400                     } else {
2401                         // exponent == -127 ==> threshShift = 53 - 2 + (-149) - (-127) = 53 - 24
2402                         int threshShift = (int) ((DoubleConsts.SIGNIFICAND_WIDTH - 2 + FloatConsts.MIN_SUB_EXPONENT) - exponent);
2403                         assert threshShift >= DoubleConsts.SIGNIFICAND_WIDTH - FloatConsts.SIGNIFICAND_WIDTH;
2404                         assert threshShift < DoubleConsts.SIGNIFICAND_WIDTH;
2405                         boolean floatSticky = (significand & ((1L << threshShift) - 1)) != 0 || round || sticky;
2406                         int iValue = (int) (significand >>> threshShift);
2407                         if ((iValue & 3) != 1 || floatSticky) {
2408                             iValue++;
2409                         }
2410                         floatBits |= iValue >> 1;
2411                     }
2412                 }
2413                 float fValue = Float.intBitsToFloat(floatBits);
2414 
2415                 // Check for overflow and update exponent accordingly.
2416                 if (exponent > Double.MAX_EXPONENT) {         // Infinite result
2417                     // overflow to properly signed infinity
2418                     return isNegative ? A2BC_NEGATIVE_INFINITY : A2BC_POSITIVE_INFINITY;
2419                 } else {  // Finite return value
2420                     if (exponent <= Double.MAX_EXPONENT && // (Usually) normal result
2421                             exponent >= Double.MIN_EXPONENT) {
2422 
2423                         // The result returned in this block cannot be a
2424                         // zero or subnormal; however after the
2425                         // significand is adjusted from rounding, we could
2426                         // still overflow in infinity.
2427 
2428                         // AND exponent bits into significand; if the
2429                         // significand is incremented and overflows from
2430                         // rounding, this combination will update the
2431                         // exponent correctly, even in the case of
2432                         // Double.MAX_VALUE overflowing to infinity.
2433 
2434                         significand = ((( exponent +
2435                                 (long) DoubleConsts.EXP_BIAS) <<
2436                                 (DoubleConsts.SIGNIFICAND_WIDTH - 1))
2437                                 & DoubleConsts.EXP_BIT_MASK) |
2438                                 (DoubleConsts.SIGNIF_BIT_MASK & significand);
2439 
2440                     } else {  // Subnormal or zero
2441                         // (exponent < Double.MIN_EXPONENT)
2442 
2443                         if (exponent < (DoubleConsts.MIN_SUB_EXPONENT - 1)) {
2444                             // No way to round back to nonzero value
2445                             // regardless of significand if the exponent is
2446                             // less than -1075.
2447                             return isNegative ? A2BC_NEGATIVE_ZERO : A2BC_POSITIVE_ZERO;
2448                         } else { //  -1075 <= exponent <= MIN_EXPONENT -1 = -1023
2449                             //
2450                             // Find bit position to round to; recompute
2451                             // round and sticky bits, and shift
2452                             // significand right appropriately.
2453                             //
2454 
2455                             sticky = sticky || round;
2456                             round = false;
2457 
2458                             // Number of bits of significand to preserve is
2459                             // exponent - abs_min_exp +1
2460                             // check:
2461                             // -1075 +1074 + 1 = 0
2462                             // -1023 +1074 + 1 = 52
2463 
2464                             int bitsDiscarded = 53 -
2465                                     ((int) exponent - DoubleConsts.MIN_SUB_EXPONENT + 1);
2466                             assert bitsDiscarded >= 1 && bitsDiscarded <= 53;
2467 
2468                             // What to do here:
2469                             // First, isolate the new round bit
2470                             round = (significand & (1L << (bitsDiscarded - 1))) != 0L;
2471                             if (bitsDiscarded > 1) {
2472                                 // create mask to update sticky bits; low
2473                                 // order bitsDiscarded bits should be 1
2474                                 long mask = ~((~0L) << (bitsDiscarded - 1));
2475                                 sticky = sticky || ((significand & mask) != 0L);
2476                             }
2477 
2478                             // Now, discard the bits
2479                             significand = significand >> bitsDiscarded;
2480 
2481                             significand = ((((long) (Double.MIN_EXPONENT - 1) + // subnorm exp.
2482                                     (long) DoubleConsts.EXP_BIAS) <<
2483                                     (DoubleConsts.SIGNIFICAND_WIDTH - 1))
2484                                     & DoubleConsts.EXP_BIT_MASK) |
2485                                     (DoubleConsts.SIGNIF_BIT_MASK & significand);
2486                         }
2487                     }
2488 
2489                     // The significand variable now contains the currently
2490                     // appropriate exponent bits too.
2491 
2492                     //
2493                     // Determine if significand should be incremented;
2494                     // making this determination depends on the least
2495                     // significant bit and the round and sticky bits.
2496                     //
2497                     // Round to nearest even rounding table, adapted from
2498                     // table 4.7 in "Computer Arithmetic" by IsraelKoren.
2499                     // The digit to the left of the "decimal" point is the
2500                     // least significant bit, the digits to the right of
2501                     // the point are the round and sticky bits
2502                     //
2503                     // Number       Round(x)
2504                     // x0.00        x0.
2505                     // x0.01        x0.
2506                     // x0.10        x0.
2507                     // x0.11        x1. = x0. +1
2508                     // x1.00        x1.
2509                     // x1.01        x1.
2510                     // x1.10        x1. + 1
2511                     // x1.11        x1. + 1
2512                     //
2513                     boolean leastZero = ((significand & 1L) == 0L);
2514                     if ((leastZero && round && sticky) ||
2515                             ((!leastZero) && round)) {
2516                         significand++;
2517                     }
2518 
2519                     double value = isNegative ?
2520                             Double.longBitsToDouble(significand | DoubleConsts.SIGN_BIT_MASK) :
2521                             Double.longBitsToDouble(significand );
2522 
2523                     return new PreparedASCIIToBinaryBuffer(value, fValue);
2524                 }
2525             }
2526     }
2527 
2528     /**
2529      * Returns <code>s</code> with any leading zeros removed.
2530      */
2531     static String stripLeadingZeros(String s) {
2532         if(!s.isEmpty() && s.charAt(0)=='0') {
2533             for(int i=1; i<s.length(); i++) {
2534                 if(s.charAt(i)!='0') {
2535                     return s.substring(i);
2536                 }
2537             }
2538             return "";
2539         }
2540         return s;
2541     }
2542 
2543     /**
2544      * Extracts a hexadecimal digit from position <code>position</code>
2545      * of string <code>s</code>.
2546      */
2547     static int getHexDigit(String s, int position) {
2548         int value = Character.digit(s.charAt(position), 16);
2549         if (value <= -1 || value >= 16) {
2550             throw new AssertionError("Unexpected failure of digit conversion of " +
2551                                      s.charAt(position));
2552         }
2553         return value;
2554     }
2555 }