• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 1996, 2013, 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 sun.misc;
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      */
toJavaFormatString(double d)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      */
toJavaFormatString(float f)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      */
appendTo(double d, Appendable buf)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      */
appendTo(float f, Appendable buf)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      */
parseDouble(String s)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      */
parseFloat(String s)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          */
toJavaFormatString()134         public 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          */
appendTo(Appendable buf)140         public void appendTo(Appendable buf);
141 
142         /**
143          * Retrieves the decimal exponent most closely corresponding to this value.
144          * @return The decimal exponent.
145          */
getDecimalExponent()146         public 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          */
getDigits(char[] digits)153         public int getDigits(char[] digits);
154 
155         /**
156          * Indicates the sign of the value.
157          * @return <code>value < 0.0</code>.
158          */
isNegative()159         public 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          */
isExceptional()167         public 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          */
digitsRoundedUp()175         public 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          */
decimalDigitsExact()182         public 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         final private String image;
191         private boolean isNegative;
192 
ExceptionalBinaryToASCIIBuffer(String image, boolean isNegative)193         public ExceptionalBinaryToASCIIBuffer(String image, boolean isNegative) {
194             this.image = image;
195             this.isNegative = isNegative;
196         }
197 
198         @Override
toJavaFormatString()199         public String toJavaFormatString() {
200             return image;
201         }
202 
203         @Override
appendTo(Appendable buf)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
getDecimalExponent()215         public int getDecimalExponent() {
216             throw new IllegalArgumentException("Exceptional value does not have an exponent");
217         }
218 
219         @Override
getDigits(char[] digits)220         public int getDigits(char[] digits) {
221             throw new IllegalArgumentException("Exceptional value does not have digits");
222         }
223 
224         @Override
isNegative()225         public boolean isNegative() {
226             return isNegative;
227         }
228 
229         @Override
isExceptional()230         public boolean isExceptional() {
231             return true;
232         }
233 
234         @Override
digitsRoundedUp()235         public boolean digitsRoundedUp() {
236             throw new IllegalArgumentException("Exceptional value is not rounded");
237         }
238 
239         @Override
decimalDigitsExact()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          */
BinaryToASCIIBuffer()284         BinaryToASCIIBuffer(){
285             this.digits = new char[20];
286         }
287 
288         /**
289          * Creates a specialized value (positive and negative zeros).
290          */
BinaryToASCIIBuffer(boolean isNegative, char[] digits)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
toJavaFormatString()300         public String toJavaFormatString() {
301             int len = getChars(buffer);
302             return new String(buffer, 0, len);
303         }
304 
305         @Override
appendTo(Appendable buf)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
getDecimalExponent()318         public int getDecimalExponent() {
319             return decExponent;
320         }
321 
322         @Override
getDigits(char[] digits)323         public int getDigits(char[] digits) {
324             System.arraycopy(this.digits,firstDigitIndex,digits,0,this.nDigits);
325             return this.nDigits;
326         }
327 
328         @Override
isNegative()329         public boolean isNegative() {
330             return isNegative;
331         }
332 
333         @Override
isExceptional()334         public boolean isExceptional() {
335             return false;
336         }
337 
338         @Override
digitsRoundedUp()339         public boolean digitsRoundedUp() {
340             return decimalDigitsRoundedUp;
341         }
342 
343         @Override
decimalDigitsExact()344         public boolean decimalDigitsExact() {
345             return exactDecimalConversion;
346         }
347 
setSign(boolean isNegative)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          */
developLongDigits( int decExponent, long lvalue, int insignificantDigits )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 
dtoa( int binExp, long fractBits, int nSignificantBits, boolean isCompatibleFormat)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 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         return threadLocalBinaryToASCIIBuffer.get();
987     }
988 
989     /**
990      * A converter which can process an ASCII <code>String</code> representation
991      * of a single or double precision floating point value into a
992      * <code>float</code> or a <code>double</code>.
993      */
994     interface ASCIIToBinaryConverter {
995 
996         double doubleValue();
997 
998         float floatValue();
999 
1000     }
1001 
1002     /**
1003      * A <code>ASCIIToBinaryConverter</code> container for a <code>double</code>.
1004      */
1005     static class PreparedASCIIToBinaryBuffer implements ASCIIToBinaryConverter {
1006         final private double doubleVal;
1007         final private float floatVal;
1008 
1009         public PreparedASCIIToBinaryBuffer(double doubleVal, float floatVal) {
1010             this.doubleVal = doubleVal;
1011             this.floatVal = floatVal;
1012         }
1013 
1014         @Override
1015         public double doubleValue() {
1016             return doubleVal;
1017         }
1018 
1019         @Override
1020         public float floatValue() {
1021             return floatVal;
1022         }
1023     }
1024 
1025     static final ASCIIToBinaryConverter A2BC_POSITIVE_INFINITY = new PreparedASCIIToBinaryBuffer(Double.POSITIVE_INFINITY, Float.POSITIVE_INFINITY);
1026     static final ASCIIToBinaryConverter A2BC_NEGATIVE_INFINITY = new PreparedASCIIToBinaryBuffer(Double.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY);
1027     static final ASCIIToBinaryConverter A2BC_NOT_A_NUMBER  = new PreparedASCIIToBinaryBuffer(Double.NaN, Float.NaN);
1028     static final ASCIIToBinaryConverter A2BC_POSITIVE_ZERO = new PreparedASCIIToBinaryBuffer(0.0d, 0.0f);
1029     static final ASCIIToBinaryConverter A2BC_NEGATIVE_ZERO = new PreparedASCIIToBinaryBuffer(-0.0d, -0.0f);
1030 
1031     /**
1032      * A buffered implementation of <code>ASCIIToBinaryConverter</code>.
1033      */
1034     static class ASCIIToBinaryBuffer implements ASCIIToBinaryConverter {
1035         boolean     isNegative;
1036         int         decExponent;
1037         char        digits[];
1038         int         nDigits;
1039 
1040         ASCIIToBinaryBuffer( boolean negSign, int decExponent, char[] digits, int n)
1041         {
1042             this.isNegative = negSign;
1043             this.decExponent = decExponent;
1044             this.digits = digits;
1045             this.nDigits = n;
1046         }
1047 
1048         /**
1049          * Takes a FloatingDecimal, which we presumably just scanned in,
1050          * and finds out what its value is, as a double.
1051          *
1052          * AS A SIDE EFFECT, SET roundDir TO INDICATE PREFERRED
1053          * ROUNDING DIRECTION in case the result is really destined
1054          * for a single-precision float.
1055          */
1056         @Override
1057         public double doubleValue() {
1058             int kDigits = Math.min(nDigits, MAX_DECIMAL_DIGITS + 1);
1059             //
1060             // convert the lead kDigits to a long integer.
1061             //
1062             // (special performance hack: start to do it using int)
1063             int iValue = (int) digits[0] - (int) '0';
1064             int iDigits = Math.min(kDigits, INT_DECIMAL_DIGITS);
1065             for (int i = 1; i < iDigits; i++) {
1066                 iValue = iValue * 10 + (int) digits[i] - (int) '0';
1067             }
1068             long lValue = (long) iValue;
1069             for (int i = iDigits; i < kDigits; i++) {
1070                 lValue = lValue * 10L + (long) ((int) digits[i] - (int) '0');
1071             }
1072             double dValue = (double) lValue;
1073             int exp = decExponent - kDigits;
1074             //
1075             // lValue now contains a long integer with the value of
1076             // the first kDigits digits of the number.
1077             // dValue contains the (double) of the same.
1078             //
1079 
1080             if (nDigits <= MAX_DECIMAL_DIGITS) {
1081                 //
1082                 // possibly an easy case.
1083                 // We know that the digits can be represented
1084                 // exactly. And if the exponent isn't too outrageous,
1085                 // the whole thing can be done with one operation,
1086                 // thus one rounding error.
1087                 // Note that all our constructors trim all leading and
1088                 // trailing zeros, so simple values (including zero)
1089                 // will always end up here
1090                 //
1091                 if (exp == 0 || dValue == 0.0) {
1092                     return (isNegative) ? -dValue : dValue; // small floating integer
1093                 }
1094                 else if (exp >= 0) {
1095                     if (exp <= MAX_SMALL_TEN) {
1096                         //
1097                         // Can get the answer with one operation,
1098                         // thus one roundoff.
1099                         //
1100                         double rValue = dValue * SMALL_10_POW[exp];
1101                         return (isNegative) ? -rValue : rValue;
1102                     }
1103                     int slop = MAX_DECIMAL_DIGITS - kDigits;
1104                     if (exp <= MAX_SMALL_TEN + slop) {
1105                         //
1106                         // We can multiply dValue by 10^(slop)
1107                         // and it is still "small" and exact.
1108                         // Then we can multiply by 10^(exp-slop)
1109                         // with one rounding.
1110                         //
1111                         dValue *= SMALL_10_POW[slop];
1112                         double rValue = dValue * SMALL_10_POW[exp - slop];
1113                         return (isNegative) ? -rValue : rValue;
1114                     }
1115                     //
1116                     // Else we have a hard case with a positive exp.
1117                     //
1118                 } else {
1119                     if (exp >= -MAX_SMALL_TEN) {
1120                         //
1121                         // Can get the answer in one division.
1122                         //
1123                         double rValue = dValue / SMALL_10_POW[-exp];
1124                         return (isNegative) ? -rValue : rValue;
1125                     }
1126                     //
1127                     // Else we have a hard case with a negative exp.
1128                     //
1129                 }
1130             }
1131 
1132             //
1133             // Harder cases:
1134             // The sum of digits plus exponent is greater than
1135             // what we think we can do with one error.
1136             //
1137             // Start by approximating the right answer by,
1138             // naively, scaling by powers of 10.
1139             //
1140             if (exp > 0) {
1141                 if (decExponent > MAX_DECIMAL_EXPONENT + 1) {
1142                     //
1143                     // Lets face it. This is going to be
1144                     // Infinity. Cut to the chase.
1145                     //
1146                     return (isNegative) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
1147                 }
1148                 if ((exp & 15) != 0) {
1149                     dValue *= SMALL_10_POW[exp & 15];
1150                 }
1151                 if ((exp >>= 4) != 0) {
1152                     int j;
1153                     for (j = 0; exp > 1; j++, exp >>= 1) {
1154                         if ((exp & 1) != 0) {
1155                             dValue *= BIG_10_POW[j];
1156                         }
1157                     }
1158                     //
1159                     // The reason for the weird exp > 1 condition
1160                     // in the above loop was so that the last multiply
1161                     // would get unrolled. We handle it here.
1162                     // It could overflow.
1163                     //
1164                     double t = dValue * BIG_10_POW[j];
1165                     if (Double.isInfinite(t)) {
1166                         //
1167                         // It did overflow.
1168                         // Look more closely at the result.
1169                         // If the exponent is just one too large,
1170                         // then use the maximum finite as our estimate
1171                         // value. Else call the result infinity
1172                         // and punt it.
1173                         // ( I presume this could happen because
1174                         // rounding forces the result here to be
1175                         // an ULP or two larger than
1176                         // Double.MAX_VALUE ).
1177                         //
1178                         t = dValue / 2.0;
1179                         t *= BIG_10_POW[j];
1180                         if (Double.isInfinite(t)) {
1181                             return (isNegative) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
1182                         }
1183                         t = Double.MAX_VALUE;
1184                     }
1185                     dValue = t;
1186                 }
1187             } else if (exp < 0) {
1188                 exp = -exp;
1189                 if (decExponent < MIN_DECIMAL_EXPONENT - 1) {
1190                     //
1191                     // Lets face it. This is going to be
1192                     // zero. Cut to the chase.
1193                     //
1194                     return (isNegative) ? -0.0 : 0.0;
1195                 }
1196                 if ((exp & 15) != 0) {
1197                     dValue /= SMALL_10_POW[exp & 15];
1198                 }
1199                 if ((exp >>= 4) != 0) {
1200                     int j;
1201                     for (j = 0; exp > 1; j++, exp >>= 1) {
1202                         if ((exp & 1) != 0) {
1203                             dValue *= TINY_10_POW[j];
1204                         }
1205                     }
1206                     //
1207                     // The reason for the weird exp > 1 condition
1208                     // in the above loop was so that the last multiply
1209                     // would get unrolled. We handle it here.
1210                     // It could underflow.
1211                     //
1212                     double t = dValue * TINY_10_POW[j];
1213                     if (t == 0.0) {
1214                         //
1215                         // It did underflow.
1216                         // Look more closely at the result.
1217                         // If the exponent is just one too small,
1218                         // then use the minimum finite as our estimate
1219                         // value. Else call the result 0.0
1220                         // and punt it.
1221                         // ( I presume this could happen because
1222                         // rounding forces the result here to be
1223                         // an ULP or two less than
1224                         // Double.MIN_VALUE ).
1225                         //
1226                         t = dValue * 2.0;
1227                         t *= TINY_10_POW[j];
1228                         if (t == 0.0) {
1229                             return (isNegative) ? -0.0 : 0.0;
1230                         }
1231                         t = Double.MIN_VALUE;
1232                     }
1233                     dValue = t;
1234                 }
1235             }
1236 
1237             //
1238             // dValue is now approximately the result.
1239             // The hard part is adjusting it, by comparison
1240             // with FDBigInteger arithmetic.
1241             // Formulate the EXACT big-number result as
1242             // bigD0 * 10^exp
1243             //
1244             if (nDigits > MAX_NDIGITS) {
1245                 nDigits = MAX_NDIGITS + 1;
1246                 digits[MAX_NDIGITS] = '1';
1247             }
1248             FDBigInteger bigD0 = new FDBigInteger(lValue, digits, kDigits, nDigits);
1249             exp = decExponent - nDigits;
1250 
1251             long ieeeBits = Double.doubleToRawLongBits(dValue); // IEEE-754 bits of double candidate
1252             final int B5 = Math.max(0, -exp); // powers of 5 in bigB, value is not modified inside correctionLoop
1253             final int D5 = Math.max(0, exp); // powers of 5 in bigD, value is not modified inside correctionLoop
1254             bigD0 = bigD0.multByPow52(D5, 0);
1255             bigD0.makeImmutable();   // prevent bigD0 modification inside correctionLoop
1256             FDBigInteger bigD = null;
1257             int prevD2 = 0;
1258 
1259             correctionLoop:
1260             while (true) {
1261                 // here ieeeBits can't be NaN, Infinity or zero
1262                 int binexp = (int) (ieeeBits >>> EXP_SHIFT);
1263                 long bigBbits = ieeeBits & DoubleConsts.SIGNIF_BIT_MASK;
1264                 if (binexp > 0) {
1265                     bigBbits |= FRACT_HOB;
1266                 } else { // Normalize denormalized numbers.
1267                     assert bigBbits != 0L : bigBbits; // doubleToBigInt(0.0)
1268                     int leadingZeros = Long.numberOfLeadingZeros(bigBbits);
1269                     int shift = leadingZeros - (63 - EXP_SHIFT);
1270                     bigBbits <<= shift;
1271                     binexp = 1 - shift;
1272                 }
1273                 binexp -= DoubleConsts.EXP_BIAS;
1274                 int lowOrderZeros = Long.numberOfTrailingZeros(bigBbits);
1275                 bigBbits >>>= lowOrderZeros;
1276                 final int bigIntExp = binexp - EXP_SHIFT + lowOrderZeros;
1277                 final int bigIntNBits = EXP_SHIFT + 1 - lowOrderZeros;
1278 
1279                 //
1280                 // Scale bigD, bigB appropriately for
1281                 // big-integer operations.
1282                 // Naively, we multiply by powers of ten
1283                 // and powers of two. What we actually do
1284                 // is keep track of the powers of 5 and
1285                 // powers of 2 we would use, then factor out
1286                 // common divisors before doing the work.
1287                 //
1288                 int B2 = B5; // powers of 2 in bigB
1289                 int D2 = D5; // powers of 2 in bigD
1290                 int Ulp2;   // powers of 2 in halfUlp.
1291                 if (bigIntExp >= 0) {
1292                     B2 += bigIntExp;
1293                 } else {
1294                     D2 -= bigIntExp;
1295                 }
1296                 Ulp2 = B2;
1297                 // shift bigB and bigD left by a number s. t.
1298                 // halfUlp is still an integer.
1299                 int hulpbias;
1300                 if (binexp <= -DoubleConsts.EXP_BIAS) {
1301                     // This is going to be a denormalized number
1302                     // (if not actually zero).
1303                     // half an ULP is at 2^-(DoubleConsts.EXP_BIAS+EXP_SHIFT+1)
1304                     hulpbias = binexp + lowOrderZeros + DoubleConsts.EXP_BIAS;
1305                 } else {
1306                     hulpbias = 1 + lowOrderZeros;
1307                 }
1308                 B2 += hulpbias;
1309                 D2 += hulpbias;
1310                 // if there are common factors of 2, we might just as well
1311                 // factor them out, as they add nothing useful.
1312                 int common2 = Math.min(B2, Math.min(D2, Ulp2));
1313                 B2 -= common2;
1314                 D2 -= common2;
1315                 Ulp2 -= common2;
1316                 // do multiplications by powers of 5 and 2
1317                 FDBigInteger bigB = FDBigInteger.valueOfMulPow52(bigBbits, B5, B2);
1318                 if (bigD == null || prevD2 != D2) {
1319                     bigD = bigD0.leftShift(D2);
1320                     prevD2 = D2;
1321                 }
1322                 //
1323                 // to recap:
1324                 // bigB is the scaled-big-int version of our floating-point
1325                 // candidate.
1326                 // bigD is the scaled-big-int version of the exact value
1327                 // as we understand it.
1328                 // halfUlp is 1/2 an ulp of bigB, except for special cases
1329                 // of exact powers of 2
1330                 //
1331                 // the plan is to compare bigB with bigD, and if the difference
1332                 // is less than halfUlp, then we're satisfied. Otherwise,
1333                 // use the ratio of difference to halfUlp to calculate a fudge
1334                 // factor to add to the floating value, then go 'round again.
1335                 //
1336                 FDBigInteger diff;
1337                 int cmpResult;
1338                 boolean overvalue;
1339                 if ((cmpResult = bigB.cmp(bigD)) > 0) {
1340                     overvalue = true; // our candidate is too big.
1341                     diff = bigB.leftInplaceSub(bigD); // bigB is not user further - reuse
1342                     if ((bigIntNBits == 1) && (bigIntExp > -DoubleConsts.EXP_BIAS + 1)) {
1343                         // candidate is a normalized exact power of 2 and
1344                         // is too big (larger than Double.MIN_NORMAL). We will be subtracting.
1345                         // For our purposes, ulp is the ulp of the
1346                         // next smaller range.
1347                         Ulp2 -= 1;
1348                         if (Ulp2 < 0) {
1349                             // rats. Cannot de-scale ulp this far.
1350                             // must scale diff in other direction.
1351                             Ulp2 = 0;
1352                             diff = diff.leftShift(1);
1353                         }
1354                     }
1355                 } else if (cmpResult < 0) {
1356                     overvalue = false; // our candidate is too small.
1357                     diff = bigD.rightInplaceSub(bigB); // bigB is not user further - reuse
1358                 } else {
1359                     // the candidate is exactly right!
1360                     // this happens with surprising frequency
1361                     break correctionLoop;
1362                 }
1363                 cmpResult = diff.cmpPow52(B5, Ulp2);
1364                 if ((cmpResult) < 0) {
1365                     // difference is small.
1366                     // this is close enough
1367                     break correctionLoop;
1368                 } else if (cmpResult == 0) {
1369                     // difference is exactly half an ULP
1370                     // round to some other value maybe, then finish
1371                     if ((ieeeBits & 1) != 0) { // half ties to even
1372                         ieeeBits += overvalue ? -1 : 1; // nextDown or nextUp
1373                     }
1374                     break correctionLoop;
1375                 } else {
1376                     // difference is non-trivial.
1377                     // could scale addend by ratio of difference to
1378                     // halfUlp here, if we bothered to compute that difference.
1379                     // Most of the time ( I hope ) it is about 1 anyway.
1380                     ieeeBits += overvalue ? -1 : 1; // nextDown or nextUp
1381                     if (ieeeBits == 0 || ieeeBits == DoubleConsts.EXP_BIT_MASK) { // 0.0 or Double.POSITIVE_INFINITY
1382                         break correctionLoop; // oops. Fell off end of range.
1383                     }
1384                     continue; // try again.
1385                 }
1386 
1387             }
1388             if (isNegative) {
1389                 ieeeBits |= DoubleConsts.SIGN_BIT_MASK;
1390             }
1391             return Double.longBitsToDouble(ieeeBits);
1392         }
1393 
1394         /**
1395          * Takes a FloatingDecimal, which we presumably just scanned in,
1396          * and finds out what its value is, as a float.
1397          * This is distinct from doubleValue() to avoid the extremely
1398          * unlikely case of a double rounding error, wherein the conversion
1399          * to double has one rounding error, and the conversion of that double
1400          * to a float has another rounding error, IN THE WRONG DIRECTION,
1401          * ( because of the preference to a zero low-order bit ).
1402          */
1403         @Override
floatValue()1404         public float floatValue() {
1405             int kDigits = Math.min(nDigits, SINGLE_MAX_DECIMAL_DIGITS + 1);
1406             //
1407             // convert the lead kDigits to an integer.
1408             //
1409             int iValue = (int) digits[0] - (int) '0';
1410             for (int i = 1; i < kDigits; i++) {
1411                 iValue = iValue * 10 + (int) digits[i] - (int) '0';
1412             }
1413             float fValue = (float) iValue;
1414             int exp = decExponent - kDigits;
1415             //
1416             // iValue now contains an integer with the value of
1417             // the first kDigits digits of the number.
1418             // fValue contains the (float) of the same.
1419             //
1420 
1421             if (nDigits <= SINGLE_MAX_DECIMAL_DIGITS) {
1422                 //
1423                 // possibly an easy case.
1424                 // We know that the digits can be represented
1425                 // exactly. And if the exponent isn't too outrageous,
1426                 // the whole thing can be done with one operation,
1427                 // thus one rounding error.
1428                 // Note that all our constructors trim all leading and
1429                 // trailing zeros, so simple values (including zero)
1430                 // will always end up here.
1431                 //
1432                 if (exp == 0 || fValue == 0.0f) {
1433                     return (isNegative) ? -fValue : fValue; // small floating integer
1434                 } else if (exp >= 0) {
1435                     if (exp <= SINGLE_MAX_SMALL_TEN) {
1436                         //
1437                         // Can get the answer with one operation,
1438                         // thus one roundoff.
1439                         //
1440                         fValue *= SINGLE_SMALL_10_POW[exp];
1441                         return (isNegative) ? -fValue : fValue;
1442                     }
1443                     int slop = SINGLE_MAX_DECIMAL_DIGITS - kDigits;
1444                     if (exp <= SINGLE_MAX_SMALL_TEN + slop) {
1445                         //
1446                         // We can multiply fValue by 10^(slop)
1447                         // and it is still "small" and exact.
1448                         // Then we can multiply by 10^(exp-slop)
1449                         // with one rounding.
1450                         //
1451                         fValue *= SINGLE_SMALL_10_POW[slop];
1452                         fValue *= SINGLE_SMALL_10_POW[exp - slop];
1453                         return (isNegative) ? -fValue : fValue;
1454                     }
1455                     //
1456                     // Else we have a hard case with a positive exp.
1457                     //
1458                 } else {
1459                     if (exp >= -SINGLE_MAX_SMALL_TEN) {
1460                         //
1461                         // Can get the answer in one division.
1462                         //
1463                         fValue /= SINGLE_SMALL_10_POW[-exp];
1464                         return (isNegative) ? -fValue : fValue;
1465                     }
1466                     //
1467                     // Else we have a hard case with a negative exp.
1468                     //
1469                 }
1470             } else if ((decExponent >= nDigits) && (nDigits + decExponent <= MAX_DECIMAL_DIGITS)) {
1471                 //
1472                 // In double-precision, this is an exact floating integer.
1473                 // So we can compute to double, then shorten to float
1474                 // with one round, and get the right answer.
1475                 //
1476                 // First, finish accumulating digits.
1477                 // Then convert that integer to a double, multiply
1478                 // by the appropriate power of ten, and convert to float.
1479                 //
1480                 long lValue = (long) iValue;
1481                 for (int i = kDigits; i < nDigits; i++) {
1482                     lValue = lValue * 10L + (long) ((int) digits[i] - (int) '0');
1483                 }
1484                 double dValue = (double) lValue;
1485                 exp = decExponent - nDigits;
1486                 dValue *= SMALL_10_POW[exp];
1487                 fValue = (float) dValue;
1488                 return (isNegative) ? -fValue : fValue;
1489 
1490             }
1491             //
1492             // Harder cases:
1493             // The sum of digits plus exponent is greater than
1494             // what we think we can do with one error.
1495             //
1496             // Start by approximating the right answer by,
1497             // naively, scaling by powers of 10.
1498             // Scaling uses doubles to avoid overflow/underflow.
1499             //
1500             double dValue = fValue;
1501             if (exp > 0) {
1502                 if (decExponent > SINGLE_MAX_DECIMAL_EXPONENT + 1) {
1503                     //
1504                     // Lets face it. This is going to be
1505                     // Infinity. Cut to the chase.
1506                     //
1507                     return (isNegative) ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
1508                 }
1509                 if ((exp & 15) != 0) {
1510                     dValue *= SMALL_10_POW[exp & 15];
1511                 }
1512                 if ((exp >>= 4) != 0) {
1513                     int j;
1514                     for (j = 0; exp > 0; j++, exp >>= 1) {
1515                         if ((exp & 1) != 0) {
1516                             dValue *= BIG_10_POW[j];
1517                         }
1518                     }
1519                 }
1520             } else if (exp < 0) {
1521                 exp = -exp;
1522                 if (decExponent < SINGLE_MIN_DECIMAL_EXPONENT - 1) {
1523                     //
1524                     // Lets face it. This is going to be
1525                     // zero. Cut to the chase.
1526                     //
1527                     return (isNegative) ? -0.0f : 0.0f;
1528                 }
1529                 if ((exp & 15) != 0) {
1530                     dValue /= SMALL_10_POW[exp & 15];
1531                 }
1532                 if ((exp >>= 4) != 0) {
1533                     int j;
1534                     for (j = 0; exp > 0; j++, exp >>= 1) {
1535                         if ((exp & 1) != 0) {
1536                             dValue *= TINY_10_POW[j];
1537                         }
1538                     }
1539                 }
1540             }
1541             fValue = Math.max(Float.MIN_VALUE, Math.min(Float.MAX_VALUE, (float) dValue));
1542 
1543             //
1544             // fValue is now approximately the result.
1545             // The hard part is adjusting it, by comparison
1546             // with FDBigInteger arithmetic.
1547             // Formulate the EXACT big-number result as
1548             // bigD0 * 10^exp
1549             //
1550             if (nDigits > SINGLE_MAX_NDIGITS) {
1551                 nDigits = SINGLE_MAX_NDIGITS + 1;
1552                 digits[SINGLE_MAX_NDIGITS] = '1';
1553             }
1554             FDBigInteger bigD0 = new FDBigInteger(iValue, digits, kDigits, nDigits);
1555             exp = decExponent - nDigits;
1556 
1557             int ieeeBits = Float.floatToRawIntBits(fValue); // IEEE-754 bits of float candidate
1558             final int B5 = Math.max(0, -exp); // powers of 5 in bigB, value is not modified inside correctionLoop
1559             final int D5 = Math.max(0, exp); // powers of 5 in bigD, value is not modified inside correctionLoop
1560             bigD0 = bigD0.multByPow52(D5, 0);
1561             bigD0.makeImmutable();   // prevent bigD0 modification inside correctionLoop
1562             FDBigInteger bigD = null;
1563             int prevD2 = 0;
1564 
1565             correctionLoop:
1566             while (true) {
1567                 // here ieeeBits can't be NaN, Infinity or zero
1568                 int binexp = ieeeBits >>> SINGLE_EXP_SHIFT;
1569                 int bigBbits = ieeeBits & FloatConsts.SIGNIF_BIT_MASK;
1570                 if (binexp > 0) {
1571                     bigBbits |= SINGLE_FRACT_HOB;
1572                 } else { // Normalize denormalized numbers.
1573                     assert bigBbits != 0 : bigBbits; // floatToBigInt(0.0)
1574                     int leadingZeros = Integer.numberOfLeadingZeros(bigBbits);
1575                     int shift = leadingZeros - (31 - SINGLE_EXP_SHIFT);
1576                     bigBbits <<= shift;
1577                     binexp = 1 - shift;
1578                 }
1579                 binexp -= FloatConsts.EXP_BIAS;
1580                 int lowOrderZeros = Integer.numberOfTrailingZeros(bigBbits);
1581                 bigBbits >>>= lowOrderZeros;
1582                 final int bigIntExp = binexp - SINGLE_EXP_SHIFT + lowOrderZeros;
1583                 final int bigIntNBits = SINGLE_EXP_SHIFT + 1 - lowOrderZeros;
1584 
1585                 //
1586                 // Scale bigD, bigB appropriately for
1587                 // big-integer operations.
1588                 // Naively, we multiply by powers of ten
1589                 // and powers of two. What we actually do
1590                 // is keep track of the powers of 5 and
1591                 // powers of 2 we would use, then factor out
1592                 // common divisors before doing the work.
1593                 //
1594                 int B2 = B5; // powers of 2 in bigB
1595                 int D2 = D5; // powers of 2 in bigD
1596                 int Ulp2;   // powers of 2 in halfUlp.
1597                 if (bigIntExp >= 0) {
1598                     B2 += bigIntExp;
1599                 } else {
1600                     D2 -= bigIntExp;
1601                 }
1602                 Ulp2 = B2;
1603                 // shift bigB and bigD left by a number s. t.
1604                 // halfUlp is still an integer.
1605                 int hulpbias;
1606                 if (binexp <= -FloatConsts.EXP_BIAS) {
1607                     // This is going to be a denormalized number
1608                     // (if not actually zero).
1609                     // half an ULP is at 2^-(FloatConsts.EXP_BIAS+SINGLE_EXP_SHIFT+1)
1610                     hulpbias = binexp + lowOrderZeros + FloatConsts.EXP_BIAS;
1611                 } else {
1612                     hulpbias = 1 + lowOrderZeros;
1613                 }
1614                 B2 += hulpbias;
1615                 D2 += hulpbias;
1616                 // if there are common factors of 2, we might just as well
1617                 // factor them out, as they add nothing useful.
1618                 int common2 = Math.min(B2, Math.min(D2, Ulp2));
1619                 B2 -= common2;
1620                 D2 -= common2;
1621                 Ulp2 -= common2;
1622                 // do multiplications by powers of 5 and 2
1623                 FDBigInteger bigB = FDBigInteger.valueOfMulPow52(bigBbits, B5, B2);
1624                 if (bigD == null || prevD2 != D2) {
1625                     bigD = bigD0.leftShift(D2);
1626                     prevD2 = D2;
1627                 }
1628                 //
1629                 // to recap:
1630                 // bigB is the scaled-big-int version of our floating-point
1631                 // candidate.
1632                 // bigD is the scaled-big-int version of the exact value
1633                 // as we understand it.
1634                 // halfUlp is 1/2 an ulp of bigB, except for special cases
1635                 // of exact powers of 2
1636                 //
1637                 // the plan is to compare bigB with bigD, and if the difference
1638                 // is less than halfUlp, then we're satisfied. Otherwise,
1639                 // use the ratio of difference to halfUlp to calculate a fudge
1640                 // factor to add to the floating value, then go 'round again.
1641                 //
1642                 FDBigInteger diff;
1643                 int cmpResult;
1644                 boolean overvalue;
1645                 if ((cmpResult = bigB.cmp(bigD)) > 0) {
1646                     overvalue = true; // our candidate is too big.
1647                     diff = bigB.leftInplaceSub(bigD); // bigB is not user further - reuse
1648                     if ((bigIntNBits == 1) && (bigIntExp > -FloatConsts.EXP_BIAS + 1)) {
1649                         // candidate is a normalized exact power of 2 and
1650                         // is too big (larger than Float.MIN_NORMAL). We will be subtracting.
1651                         // For our purposes, ulp is the ulp of the
1652                         // next smaller range.
1653                         Ulp2 -= 1;
1654                         if (Ulp2 < 0) {
1655                             // rats. Cannot de-scale ulp this far.
1656                             // must scale diff in other direction.
1657                             Ulp2 = 0;
1658                             diff = diff.leftShift(1);
1659                         }
1660                     }
1661                 } else if (cmpResult < 0) {
1662                     overvalue = false; // our candidate is too small.
1663                     diff = bigD.rightInplaceSub(bigB); // bigB is not user further - reuse
1664                 } else {
1665                     // the candidate is exactly right!
1666                     // this happens with surprising frequency
1667                     break correctionLoop;
1668                 }
1669                 cmpResult = diff.cmpPow52(B5, Ulp2);
1670                 if ((cmpResult) < 0) {
1671                     // difference is small.
1672                     // this is close enough
1673                     break correctionLoop;
1674                 } else if (cmpResult == 0) {
1675                     // difference is exactly half an ULP
1676                     // round to some other value maybe, then finish
1677                     if ((ieeeBits & 1) != 0) { // half ties to even
1678                         ieeeBits += overvalue ? -1 : 1; // nextDown or nextUp
1679                     }
1680                     break correctionLoop;
1681                 } else {
1682                     // difference is non-trivial.
1683                     // could scale addend by ratio of difference to
1684                     // halfUlp here, if we bothered to compute that difference.
1685                     // Most of the time ( I hope ) it is about 1 anyway.
1686                     ieeeBits += overvalue ? -1 : 1; // nextDown or nextUp
1687                     if (ieeeBits == 0 || ieeeBits == FloatConsts.EXP_BIT_MASK) { // 0.0 or Float.POSITIVE_INFINITY
1688                         break correctionLoop; // oops. Fell off end of range.
1689                     }
1690                     continue; // try again.
1691                 }
1692 
1693             }
1694             if (isNegative) {
1695                 ieeeBits |= FloatConsts.SIGN_BIT_MASK;
1696             }
1697             return Float.intBitsToFloat(ieeeBits);
1698         }
1699 
1700 
1701         /**
1702          * All the positive powers of 10 that can be
1703          * represented exactly in double/float.
1704          */
1705         private static final double[] SMALL_10_POW = {
1706             1.0e0,
1707             1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5,
1708             1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10,
1709             1.0e11, 1.0e12, 1.0e13, 1.0e14, 1.0e15,
1710             1.0e16, 1.0e17, 1.0e18, 1.0e19, 1.0e20,
1711             1.0e21, 1.0e22
1712         };
1713 
1714         private static final float[] SINGLE_SMALL_10_POW = {
1715             1.0e0f,
1716             1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,
1717             1.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f
1718         };
1719 
1720         private static final double[] BIG_10_POW = {
1721             1e16, 1e32, 1e64, 1e128, 1e256 };
1722         private static final double[] TINY_10_POW = {
1723             1e-16, 1e-32, 1e-64, 1e-128, 1e-256 };
1724 
1725         private static final int MAX_SMALL_TEN = SMALL_10_POW.length-1;
1726         private static final int SINGLE_MAX_SMALL_TEN = SINGLE_SMALL_10_POW.length-1;
1727 
1728     }
1729 
1730     /**
1731      * Returns a <code>BinaryToASCIIConverter</code> for a <code>double</code>.
1732      * The returned object is a <code>ThreadLocal</code> variable of this class.
1733      *
1734      * @param d The double precision value to convert.
1735      * @return The converter.
1736      */
getBinaryToASCIIConverter(double d)1737     public static BinaryToASCIIConverter getBinaryToASCIIConverter(double d) {
1738         return getBinaryToASCIIConverter(d, true);
1739     }
1740 
1741     /**
1742      * Returns a <code>BinaryToASCIIConverter</code> for a <code>double</code>.
1743      * The returned object is a <code>ThreadLocal</code> variable of this class.
1744      *
1745      * @param d The double precision value to convert.
1746      * @param isCompatibleFormat
1747      * @return The converter.
1748      */
getBinaryToASCIIConverter(double d, boolean isCompatibleFormat)1749     static BinaryToASCIIConverter getBinaryToASCIIConverter(double d, boolean isCompatibleFormat) {
1750         long dBits = Double.doubleToRawLongBits(d);
1751         boolean isNegative = (dBits&DoubleConsts.SIGN_BIT_MASK) != 0; // discover sign
1752         long fractBits = dBits & DoubleConsts.SIGNIF_BIT_MASK;
1753         int  binExp = (int)( (dBits&DoubleConsts.EXP_BIT_MASK) >> EXP_SHIFT );
1754         // Discover obvious special cases of NaN and Infinity.
1755         if ( binExp == (int)(DoubleConsts.EXP_BIT_MASK>>EXP_SHIFT) ) {
1756             if ( fractBits == 0L ){
1757                 return isNegative ? B2AC_NEGATIVE_INFINITY : B2AC_POSITIVE_INFINITY;
1758             } else {
1759                 return B2AC_NOT_A_NUMBER;
1760             }
1761         }
1762         // Finish unpacking
1763         // Normalize denormalized numbers.
1764         // Insert assumed high-order bit for normalized numbers.
1765         // Subtract exponent bias.
1766         int  nSignificantBits;
1767         if ( binExp == 0 ){
1768             if ( fractBits == 0L ){
1769                 // not a denorm, just a 0!
1770                 return isNegative ? B2AC_NEGATIVE_ZERO : B2AC_POSITIVE_ZERO;
1771             }
1772             int leadingZeros = Long.numberOfLeadingZeros(fractBits);
1773             int shift = leadingZeros-(63-EXP_SHIFT);
1774             fractBits <<= shift;
1775             binExp = 1 - shift;
1776             nSignificantBits =  64-leadingZeros; // recall binExp is  - shift count.
1777         } else {
1778             fractBits |= FRACT_HOB;
1779             nSignificantBits = EXP_SHIFT+1;
1780         }
1781         binExp -= DoubleConsts.EXP_BIAS;
1782         BinaryToASCIIBuffer buf = getBinaryToASCIIBuffer();
1783         buf.setSign(isNegative);
1784         // call the routine that actually does all the hard work.
1785         buf.dtoa(binExp, fractBits, nSignificantBits, isCompatibleFormat);
1786         return buf;
1787     }
1788 
getBinaryToASCIIConverter(float f)1789     private static BinaryToASCIIConverter getBinaryToASCIIConverter(float f) {
1790         int fBits = Float.floatToRawIntBits( f );
1791         boolean isNegative = (fBits&FloatConsts.SIGN_BIT_MASK) != 0;
1792         int fractBits = fBits&FloatConsts.SIGNIF_BIT_MASK;
1793         int binExp = (fBits&FloatConsts.EXP_BIT_MASK) >> SINGLE_EXP_SHIFT;
1794         // Discover obvious special cases of NaN and Infinity.
1795         if ( binExp == (FloatConsts.EXP_BIT_MASK>>SINGLE_EXP_SHIFT) ) {
1796             if ( fractBits == 0L ){
1797                 return isNegative ? B2AC_NEGATIVE_INFINITY : B2AC_POSITIVE_INFINITY;
1798             } else {
1799                 return B2AC_NOT_A_NUMBER;
1800             }
1801         }
1802         // Finish unpacking
1803         // Normalize denormalized numbers.
1804         // Insert assumed high-order bit for normalized numbers.
1805         // Subtract exponent bias.
1806         int  nSignificantBits;
1807         if ( binExp == 0 ){
1808             if ( fractBits == 0 ){
1809                 // not a denorm, just a 0!
1810                 return isNegative ? B2AC_NEGATIVE_ZERO : B2AC_POSITIVE_ZERO;
1811             }
1812             int leadingZeros = Integer.numberOfLeadingZeros(fractBits);
1813             int shift = leadingZeros-(31-SINGLE_EXP_SHIFT);
1814             fractBits <<= shift;
1815             binExp = 1 - shift;
1816             nSignificantBits =  32 - leadingZeros; // recall binExp is  - shift count.
1817         } else {
1818             fractBits |= SINGLE_FRACT_HOB;
1819             nSignificantBits = SINGLE_EXP_SHIFT+1;
1820         }
1821         binExp -= FloatConsts.EXP_BIAS;
1822         BinaryToASCIIBuffer buf = getBinaryToASCIIBuffer();
1823         buf.setSign(isNegative);
1824         // call the routine that actually does all the hard work.
1825         buf.dtoa(binExp, ((long)fractBits)<<(EXP_SHIFT-SINGLE_EXP_SHIFT), nSignificantBits, true);
1826         return buf;
1827     }
1828 
1829     @SuppressWarnings("fallthrough")
readJavaFormatString( String in )1830     static ASCIIToBinaryConverter readJavaFormatString( String in ) throws NumberFormatException {
1831         boolean isNegative = false;
1832         boolean signSeen   = false;
1833         int     decExp;
1834         char    c;
1835 
1836     parseNumber:
1837         try{
1838             in = in.trim(); // don't fool around with white space.
1839                             // throws NullPointerException if null
1840             int len = in.length();
1841             if ( len == 0 ) {
1842                 throw new NumberFormatException("empty String");
1843             }
1844             int i = 0;
1845             switch (in.charAt(i)){
1846             case '-':
1847                 isNegative = true;
1848                 //FALLTHROUGH
1849             case '+':
1850                 i++;
1851                 signSeen = true;
1852             }
1853             c = in.charAt(i);
1854             if(c == 'N') { // Check for NaN
1855                 if((len-i)==NAN_LENGTH && in.indexOf(NAN_REP,i)==i) {
1856                     return A2BC_NOT_A_NUMBER;
1857                 }
1858                 // something went wrong, throw exception
1859                 break parseNumber;
1860             } else if(c == 'I') { // Check for Infinity strings
1861                 if((len-i)==INFINITY_LENGTH && in.indexOf(INFINITY_REP,i)==i) {
1862                     return isNegative? A2BC_NEGATIVE_INFINITY : A2BC_POSITIVE_INFINITY;
1863                 }
1864                 // something went wrong, throw exception
1865                 break parseNumber;
1866             } else if (c == '0')  { // check for hexadecimal floating-point number
1867                 if (len > i+1 ) {
1868                     char ch = in.charAt(i+1);
1869                     if (ch == 'x' || ch == 'X' ) { // possible hex string
1870                         return parseHexString(in);
1871                     }
1872                 }
1873             }  // look for and process decimal floating-point string
1874 
1875             char[] digits = new char[ len ];
1876             int    nDigits= 0;
1877             boolean decSeen = false;
1878             int decPt = 0;
1879             int nLeadZero = 0;
1880             int nTrailZero= 0;
1881 
1882         skipLeadingZerosLoop:
1883             while (i < len) {
1884                 c = in.charAt(i);
1885                 if (c == '0') {
1886                     nLeadZero++;
1887                 } else if (c == '.') {
1888                     if (decSeen) {
1889                         // already saw one ., this is the 2nd.
1890                         throw new NumberFormatException("multiple points");
1891                     }
1892                     decPt = i;
1893                     if (signSeen) {
1894                         decPt -= 1;
1895                     }
1896                     decSeen = true;
1897                 } else {
1898                     break skipLeadingZerosLoop;
1899                 }
1900                 i++;
1901             }
1902         digitLoop:
1903             while (i < len) {
1904                 c = in.charAt(i);
1905                 if (c >= '1' && c <= '9') {
1906                     digits[nDigits++] = c;
1907                     nTrailZero = 0;
1908                 } else if (c == '0') {
1909                     digits[nDigits++] = c;
1910                     nTrailZero++;
1911                 } else if (c == '.') {
1912                     if (decSeen) {
1913                         // already saw one ., this is the 2nd.
1914                         throw new NumberFormatException("multiple points");
1915                     }
1916                     decPt = i;
1917                     if (signSeen) {
1918                         decPt -= 1;
1919                     }
1920                     decSeen = true;
1921                 } else {
1922                     break digitLoop;
1923                 }
1924                 i++;
1925             }
1926             nDigits -=nTrailZero;
1927             //
1928             // At this point, we've scanned all the digits and decimal
1929             // point we're going to see. Trim off leading and trailing
1930             // zeros, which will just confuse us later, and adjust
1931             // our initial decimal exponent accordingly.
1932             // To review:
1933             // we have seen i total characters.
1934             // nLeadZero of them were zeros before any other digits.
1935             // nTrailZero of them were zeros after any other digits.
1936             // if ( decSeen ), then a . was seen after decPt characters
1937             // ( including leading zeros which have been discarded )
1938             // nDigits characters were neither lead nor trailing
1939             // zeros, nor point
1940             //
1941             //
1942             // special hack: if we saw no non-zero digits, then the
1943             // answer is zero!
1944             // Unfortunately, we feel honor-bound to keep parsing!
1945             //
1946             boolean isZero = (nDigits == 0);
1947             if ( isZero &&  nLeadZero == 0 ){
1948                 // we saw NO DIGITS AT ALL,
1949                 // not even a crummy 0!
1950                 // this is not allowed.
1951                 break parseNumber; // go throw exception
1952             }
1953             //
1954             // Our initial exponent is decPt, adjusted by the number of
1955             // discarded zeros. Or, if there was no decPt,
1956             // then its just nDigits adjusted by discarded trailing zeros.
1957             //
1958             if ( decSeen ){
1959                 decExp = decPt - nLeadZero;
1960             } else {
1961                 decExp = nDigits + nTrailZero;
1962             }
1963 
1964             //
1965             // Look for 'e' or 'E' and an optionally signed integer.
1966             //
1967             if ( (i < len) &&  (((c = in.charAt(i) )=='e') || (c == 'E') ) ){
1968                 int expSign = 1;
1969                 int expVal  = 0;
1970                 int reallyBig = Integer.MAX_VALUE / 10;
1971                 boolean expOverflow = false;
1972                 switch( in.charAt(++i) ){
1973                 case '-':
1974                     expSign = -1;
1975                     //FALLTHROUGH
1976                 case '+':
1977                     i++;
1978                 }
1979                 int expAt = i;
1980             expLoop:
1981                 while ( i < len  ){
1982                     if ( expVal >= reallyBig ){
1983                         // the next character will cause integer
1984                         // overflow.
1985                         expOverflow = true;
1986                     }
1987                     c = in.charAt(i++);
1988                     if(c>='0' && c<='9') {
1989                         expVal = expVal*10 + ( (int)c - (int)'0' );
1990                     } else {
1991                         i--;           // back up.
1992                         break expLoop; // stop parsing exponent.
1993                     }
1994                 }
1995                 int expLimit = BIG_DECIMAL_EXPONENT+nDigits+nTrailZero;
1996                 if ( expOverflow || ( expVal > expLimit ) ){
1997                     //
1998                     // The intent here is to end up with
1999                     // infinity or zero, as appropriate.
2000                     // The reason for yielding such a small decExponent,
2001                     // rather than something intuitive such as
2002                     // expSign*Integer.MAX_VALUE, is that this value
2003                     // is subject to further manipulation in
2004                     // doubleValue() and floatValue(), and I don't want
2005                     // it to be able to cause overflow there!
2006                     // (The only way we can get into trouble here is for
2007                     // really outrageous nDigits+nTrailZero, such as 2 billion. )
2008                     //
2009                     decExp = expSign*expLimit;
2010                 } else {
2011                     // this should not overflow, since we tested
2012                     // for expVal > (MAX+N), where N >= abs(decExp)
2013                     decExp = decExp + expSign*expVal;
2014                 }
2015 
2016                 // if we saw something not a digit ( or end of string )
2017                 // after the [Ee][+-], without seeing any digits at all
2018                 // this is certainly an error. If we saw some digits,
2019                 // but then some trailing garbage, that might be ok.
2020                 // so we just fall through in that case.
2021                 // HUMBUG
2022                 if ( i == expAt ) {
2023                     break parseNumber; // certainly bad
2024                 }
2025             }
2026             //
2027             // We parsed everything we could.
2028             // If there are leftovers, then this is not good input!
2029             //
2030             if ( i < len &&
2031                 ((i != len - 1) ||
2032                 (in.charAt(i) != 'f' &&
2033                  in.charAt(i) != 'F' &&
2034                  in.charAt(i) != 'd' &&
2035                  in.charAt(i) != 'D'))) {
2036                 break parseNumber; // go throw exception
2037             }
2038             if(isZero) {
2039                 return isNegative ? A2BC_NEGATIVE_ZERO : A2BC_POSITIVE_ZERO;
2040             }
2041             return new ASCIIToBinaryBuffer(isNegative, decExp, digits, nDigits);
2042         } catch ( StringIndexOutOfBoundsException e ){ }
2043         throw new NumberFormatException("For input string: \"" + in + "\"");
2044     }
2045 
2046     private static class HexFloatPattern {
2047         /**
2048          * Grammar is compatible with hexadecimal floating-point constants
2049          * described in section 6.4.4.2 of the C99 specification.
2050          */
2051         private static final Pattern VALUE = Pattern.compile(
2052                    //1           234                   56                7                   8      9
2053                     "([-+])?0[xX](((\\p{XDigit}+)\\.?)|((\\p{XDigit}*)\\.(\\p{XDigit}+)))[pP]([-+])?(\\p{Digit}+)[fFdD]?"
2054                     );
2055     }
2056 
2057     /**
2058      * Converts string s to a suitable floating decimal; uses the
2059      * double constructor and sets the roundDir variable appropriately
2060      * in case the value is later converted to a float.
2061      *
2062      * @param s The <code>String</code> to parse.
2063      */
parseHexString(String s)2064    static ASCIIToBinaryConverter parseHexString(String s) {
2065             // Verify string is a member of the hexadecimal floating-point
2066             // string language.
2067             Matcher m = HexFloatPattern.VALUE.matcher(s);
2068             boolean validInput = m.matches();
2069             if (!validInput) {
2070                 // Input does not match pattern
2071                 throw new NumberFormatException("For input string: \"" + s + "\"");
2072             } else { // validInput
2073                 //
2074                 // We must isolate the sign, significand, and exponent
2075                 // fields.  The sign value is straightforward.  Since
2076                 // floating-point numbers are stored with a normalized
2077                 // representation, the significand and exponent are
2078                 // interrelated.
2079                 //
2080                 // After extracting the sign, we normalized the
2081                 // significand as a hexadecimal value, calculating an
2082                 // exponent adjust for any shifts made during
2083                 // normalization.  If the significand is zero, the
2084                 // exponent doesn't need to be examined since the output
2085                 // will be zero.
2086                 //
2087                 // Next the exponent in the input string is extracted.
2088                 // Afterwards, the significand is normalized as a *binary*
2089                 // value and the input value's normalized exponent can be
2090                 // computed.  The significand bits are copied into a
2091                 // double significand; if the string has more logical bits
2092                 // than can fit in a double, the extra bits affect the
2093                 // round and sticky bits which are used to round the final
2094                 // value.
2095                 //
2096                 //  Extract significand sign
2097                 String group1 = m.group(1);
2098                 boolean isNegative = ((group1 != null) && group1.equals("-"));
2099 
2100                 //  Extract Significand magnitude
2101                 //
2102                 // Based on the form of the significand, calculate how the
2103                 // binary exponent needs to be adjusted to create a
2104                 // normalized//hexadecimal* floating-point number; that
2105                 // is, a number where there is one nonzero hex digit to
2106                 // the left of the (hexa)decimal point.  Since we are
2107                 // adjusting a binary, not hexadecimal exponent, the
2108                 // exponent is adjusted by a multiple of 4.
2109                 //
2110                 // There are a number of significand scenarios to consider;
2111                 // letters are used in indicate nonzero digits:
2112                 //
2113                 // 1. 000xxxx       =>      x.xxx   normalized
2114                 //    increase exponent by (number of x's - 1)*4
2115                 //
2116                 // 2. 000xxx.yyyy =>        x.xxyyyy        normalized
2117                 //    increase exponent by (number of x's - 1)*4
2118                 //
2119                 // 3. .000yyy  =>   y.yy    normalized
2120                 //    decrease exponent by (number of zeros + 1)*4
2121                 //
2122                 // 4. 000.00000yyy => y.yy normalized
2123                 //    decrease exponent by (number of zeros to right of point + 1)*4
2124                 //
2125                 // If the significand is exactly zero, return a properly
2126                 // signed zero.
2127                 //
2128 
2129                 String significandString = null;
2130                 int signifLength = 0;
2131                 int exponentAdjust = 0;
2132                 {
2133                     int leftDigits = 0; // number of meaningful digits to
2134                     // left of "decimal" point
2135                     // (leading zeros stripped)
2136                     int rightDigits = 0; // number of digits to right of
2137                     // "decimal" point; leading zeros
2138                     // must always be accounted for
2139                     //
2140                     // The significand is made up of either
2141                     //
2142                     // 1. group 4 entirely (integer portion only)
2143                     //
2144                     // OR
2145                     //
2146                     // 2. the fractional portion from group 7 plus any
2147                     // (optional) integer portions from group 6.
2148                     //
2149                     String group4;
2150                     if ((group4 = m.group(4)) != null) {  // Integer-only significand
2151                         // Leading zeros never matter on the integer portion
2152                         significandString = stripLeadingZeros(group4);
2153                         leftDigits = significandString.length();
2154                     } else {
2155                         // Group 6 is the optional integer; leading zeros
2156                         // never matter on the integer portion
2157                         String group6 = stripLeadingZeros(m.group(6));
2158                         leftDigits = group6.length();
2159 
2160                         // fraction
2161                         String group7 = m.group(7);
2162                         rightDigits = group7.length();
2163 
2164                         // Turn "integer.fraction" into "integer"+"fraction"
2165                         significandString =
2166                                 ((group6 == null) ? "" : group6) + // is the null
2167                                         // check necessary?
2168                                         group7;
2169                     }
2170 
2171                     significandString = stripLeadingZeros(significandString);
2172                     signifLength = significandString.length();
2173 
2174                     //
2175                     // Adjust exponent as described above
2176                     //
2177                     if (leftDigits >= 1) {  // Cases 1 and 2
2178                         exponentAdjust = 4 * (leftDigits - 1);
2179                     } else {                // Cases 3 and 4
2180                         exponentAdjust = -4 * (rightDigits - signifLength + 1);
2181                     }
2182 
2183                     // If the significand is zero, the exponent doesn't
2184                     // matter; return a properly signed zero.
2185 
2186                     if (signifLength == 0) { // Only zeros in input
2187                         return isNegative ? A2BC_NEGATIVE_ZERO : A2BC_POSITIVE_ZERO;
2188                     }
2189                 }
2190 
2191                 //  Extract Exponent
2192                 //
2193                 // Use an int to read in the exponent value; this should
2194                 // provide more than sufficient range for non-contrived
2195                 // inputs.  If reading the exponent in as an int does
2196                 // overflow, examine the sign of the exponent and
2197                 // significand to determine what to do.
2198                 //
2199                 String group8 = m.group(8);
2200                 boolean positiveExponent = (group8 == null) || group8.equals("+");
2201                 long unsignedRawExponent;
2202                 try {
2203                     unsignedRawExponent = Integer.parseInt(m.group(9));
2204                 }
2205                 catch (NumberFormatException e) {
2206                     // At this point, we know the exponent is
2207                     // syntactically well-formed as a sequence of
2208                     // digits.  Therefore, if an NumberFormatException
2209                     // is thrown, it must be due to overflowing int's
2210                     // range.  Also, at this point, we have already
2211                     // checked for a zero significand.  Thus the signs
2212                     // of the exponent and significand determine the
2213                     // final result:
2214                     //
2215                     //                      significand
2216                     //                      +               -
2217                     // exponent     +       +infinity       -infinity
2218                     //              -       +0.0            -0.0
2219                     return isNegative ?
2220                               (positiveExponent ? A2BC_NEGATIVE_INFINITY : A2BC_NEGATIVE_ZERO)
2221                             : (positiveExponent ? A2BC_POSITIVE_INFINITY : A2BC_POSITIVE_ZERO);
2222 
2223                 }
2224 
2225                 long rawExponent =
2226                         (positiveExponent ? 1L : -1L) * // exponent sign
2227                                 unsignedRawExponent;            // exponent magnitude
2228 
2229                 // Calculate partially adjusted exponent
2230                 long exponent = rawExponent + exponentAdjust;
2231 
2232                 // Starting copying non-zero bits into proper position in
2233                 // a long; copy explicit bit too; this will be masked
2234                 // later for normal values.
2235 
2236                 boolean round = false;
2237                 boolean sticky = false;
2238                 int nextShift = 0;
2239                 long significand = 0L;
2240                 // First iteration is different, since we only copy
2241                 // from the leading significand bit; one more exponent
2242                 // adjust will be needed...
2243 
2244                 // IMPORTANT: make leadingDigit a long to avoid
2245                 // surprising shift semantics!
2246                 long leadingDigit = getHexDigit(significandString, 0);
2247 
2248                 //
2249                 // Left shift the leading digit (53 - (bit position of
2250                 // leading 1 in digit)); this sets the top bit of the
2251                 // significand to 1.  The nextShift value is adjusted
2252                 // to take into account the number of bit positions of
2253                 // the leadingDigit actually used.  Finally, the
2254                 // exponent is adjusted to normalize the significand
2255                 // as a binary value, not just a hex value.
2256                 //
2257                 if (leadingDigit == 1) {
2258                     significand |= leadingDigit << 52;
2259                     nextShift = 52 - 4;
2260                     // exponent += 0
2261                 } else if (leadingDigit <= 3) { // [2, 3]
2262                     significand |= leadingDigit << 51;
2263                     nextShift = 52 - 5;
2264                     exponent += 1;
2265                 } else if (leadingDigit <= 7) { // [4, 7]
2266                     significand |= leadingDigit << 50;
2267                     nextShift = 52 - 6;
2268                     exponent += 2;
2269                 } else if (leadingDigit <= 15) { // [8, f]
2270                     significand |= leadingDigit << 49;
2271                     nextShift = 52 - 7;
2272                     exponent += 3;
2273                 } else {
2274                     throw new AssertionError("Result from digit conversion too large!");
2275                 }
2276                 // The preceding if-else could be replaced by a single
2277                 // code block based on the high-order bit set in
2278                 // leadingDigit.  Given leadingOnePosition,
2279 
2280                 // significand |= leadingDigit << (SIGNIFICAND_WIDTH - leadingOnePosition);
2281                 // nextShift = 52 - (3 + leadingOnePosition);
2282                 // exponent += (leadingOnePosition-1);
2283 
2284                 //
2285                 // Now the exponent variable is equal to the normalized
2286                 // binary exponent.  Code below will make representation
2287                 // adjustments if the exponent is incremented after
2288                 // rounding (includes overflows to infinity) or if the
2289                 // result is subnormal.
2290                 //
2291 
2292                 // Copy digit into significand until the significand can't
2293                 // hold another full hex digit or there are no more input
2294                 // hex digits.
2295                 int i = 0;
2296                 for (i = 1;
2297                      i < signifLength && nextShift >= 0;
2298                      i++) {
2299                     long currentDigit = getHexDigit(significandString, i);
2300                     significand |= (currentDigit << nextShift);
2301                     nextShift -= 4;
2302                 }
2303 
2304                 // After the above loop, the bulk of the string is copied.
2305                 // Now, we must copy any partial hex digits into the
2306                 // significand AND compute the round bit and start computing
2307                 // sticky bit.
2308 
2309                 if (i < signifLength) { // at least one hex input digit exists
2310                     long currentDigit = getHexDigit(significandString, i);
2311 
2312                     // from nextShift, figure out how many bits need
2313                     // to be copied, if any
2314                     switch (nextShift) { // must be negative
2315                         case -1:
2316                             // three bits need to be copied in; can
2317                             // set round bit
2318                             significand |= ((currentDigit & 0xEL) >> 1);
2319                             round = (currentDigit & 0x1L) != 0L;
2320                             break;
2321 
2322                         case -2:
2323                             // two bits need to be copied in; can
2324                             // set round and start sticky
2325                             significand |= ((currentDigit & 0xCL) >> 2);
2326                             round = (currentDigit & 0x2L) != 0L;
2327                             sticky = (currentDigit & 0x1L) != 0;
2328                             break;
2329 
2330                         case -3:
2331                             // one bit needs to be copied in
2332                             significand |= ((currentDigit & 0x8L) >> 3);
2333                             // Now set round and start sticky, if possible
2334                             round = (currentDigit & 0x4L) != 0L;
2335                             sticky = (currentDigit & 0x3L) != 0;
2336                             break;
2337 
2338                         case -4:
2339                             // all bits copied into significand; set
2340                             // round and start sticky
2341                             round = ((currentDigit & 0x8L) != 0);  // is top bit set?
2342                             // nonzeros in three low order bits?
2343                             sticky = (currentDigit & 0x7L) != 0;
2344                             break;
2345 
2346                         default:
2347                             throw new AssertionError("Unexpected shift distance remainder.");
2348                             // break;
2349                     }
2350 
2351                     // Round is set; sticky might be set.
2352 
2353                     // For the sticky bit, it suffices to check the
2354                     // current digit and test for any nonzero digits in
2355                     // the remaining unprocessed input.
2356                     i++;
2357                     while (i < signifLength && !sticky) {
2358                         currentDigit = getHexDigit(significandString, i);
2359                         sticky = sticky || (currentDigit != 0);
2360                         i++;
2361                     }
2362 
2363                 }
2364                 // else all of string was seen, round and sticky are
2365                 // correct as false.
2366 
2367                 // Float calculations
2368                 int floatBits = isNegative ? FloatConsts.SIGN_BIT_MASK : 0;
2369                 if (exponent >= FloatConsts.MIN_EXPONENT) {
2370                     if (exponent > FloatConsts.MAX_EXPONENT) {
2371                         // Float.POSITIVE_INFINITY
2372                         floatBits |= FloatConsts.EXP_BIT_MASK;
2373                     } else {
2374                         int threshShift = DoubleConsts.SIGNIFICAND_WIDTH - FloatConsts.SIGNIFICAND_WIDTH - 1;
2375                         boolean floatSticky = (significand & ((1L << threshShift) - 1)) != 0 || round || sticky;
2376                         int iValue = (int) (significand >>> threshShift);
2377                         if ((iValue & 3) != 1 || floatSticky) {
2378                             iValue++;
2379                         }
2380                         floatBits |= (((((int) exponent) + (FloatConsts.EXP_BIAS - 1))) << SINGLE_EXP_SHIFT) + (iValue >> 1);
2381                     }
2382                 } else {
2383                     if (exponent < FloatConsts.MIN_SUB_EXPONENT - 1) {
2384                         // 0
2385                     } else {
2386                         // exponent == -127 ==> threshShift = 53 - 2 + (-149) - (-127) = 53 - 24
2387                         int threshShift = (int) ((DoubleConsts.SIGNIFICAND_WIDTH - 2 + FloatConsts.MIN_SUB_EXPONENT) - exponent);
2388                         assert threshShift >= DoubleConsts.SIGNIFICAND_WIDTH - FloatConsts.SIGNIFICAND_WIDTH;
2389                         assert threshShift < DoubleConsts.SIGNIFICAND_WIDTH;
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 |= iValue >> 1;
2396                     }
2397                 }
2398                 float fValue = Float.intBitsToFloat(floatBits);
2399 
2400                 // Check for overflow and update exponent accordingly.
2401                 if (exponent > DoubleConsts.MAX_EXPONENT) {         // Infinite result
2402                     // overflow to properly signed infinity
2403                     return isNegative ? A2BC_NEGATIVE_INFINITY : A2BC_POSITIVE_INFINITY;
2404                 } else {  // Finite return value
2405                     if (exponent <= DoubleConsts.MAX_EXPONENT && // (Usually) normal result
2406                             exponent >= DoubleConsts.MIN_EXPONENT) {
2407 
2408                         // The result returned in this block cannot be a
2409                         // zero or subnormal; however after the
2410                         // significand is adjusted from rounding, we could
2411                         // still overflow in infinity.
2412 
2413                         // AND exponent bits into significand; if the
2414                         // significand is incremented and overflows from
2415                         // rounding, this combination will update the
2416                         // exponent correctly, even in the case of
2417                         // Double.MAX_VALUE overflowing to infinity.
2418 
2419                         significand = ((( exponent +
2420                                 (long) DoubleConsts.EXP_BIAS) <<
2421                                 (DoubleConsts.SIGNIFICAND_WIDTH - 1))
2422                                 & DoubleConsts.EXP_BIT_MASK) |
2423                                 (DoubleConsts.SIGNIF_BIT_MASK & significand);
2424 
2425                     } else {  // Subnormal or zero
2426                         // (exponent < DoubleConsts.MIN_EXPONENT)
2427 
2428                         if (exponent < (DoubleConsts.MIN_SUB_EXPONENT - 1)) {
2429                             // No way to round back to nonzero value
2430                             // regardless of significand if the exponent is
2431                             // less than -1075.
2432                             return isNegative ? A2BC_NEGATIVE_ZERO : A2BC_POSITIVE_ZERO;
2433                         } else { //  -1075 <= exponent <= MIN_EXPONENT -1 = -1023
2434                             //
2435                             // Find bit position to round to; recompute
2436                             // round and sticky bits, and shift
2437                             // significand right appropriately.
2438                             //
2439 
2440                             sticky = sticky || round;
2441                             round = false;
2442 
2443                             // Number of bits of significand to preserve is
2444                             // exponent - abs_min_exp +1
2445                             // check:
2446                             // -1075 +1074 + 1 = 0
2447                             // -1023 +1074 + 1 = 52
2448 
2449                             int bitsDiscarded = 53 -
2450                                     ((int) exponent - DoubleConsts.MIN_SUB_EXPONENT + 1);
2451                             assert bitsDiscarded >= 1 && bitsDiscarded <= 53;
2452 
2453                             // What to do here:
2454                             // First, isolate the new round bit
2455                             round = (significand & (1L << (bitsDiscarded - 1))) != 0L;
2456                             if (bitsDiscarded > 1) {
2457                                 // create mask to update sticky bits; low
2458                                 // order bitsDiscarded bits should be 1
2459                                 long mask = ~((~0L) << (bitsDiscarded - 1));
2460                                 sticky = sticky || ((significand & mask) != 0L);
2461                             }
2462 
2463                             // Now, discard the bits
2464                             significand = significand >> bitsDiscarded;
2465 
2466                             significand = ((((long) (DoubleConsts.MIN_EXPONENT - 1) + // subnorm exp.
2467                                     (long) DoubleConsts.EXP_BIAS) <<
2468                                     (DoubleConsts.SIGNIFICAND_WIDTH - 1))
2469                                     & DoubleConsts.EXP_BIT_MASK) |
2470                                     (DoubleConsts.SIGNIF_BIT_MASK & significand);
2471                         }
2472                     }
2473 
2474                     // The significand variable now contains the currently
2475                     // appropriate exponent bits too.
2476 
2477                     //
2478                     // Determine if significand should be incremented;
2479                     // making this determination depends on the least
2480                     // significant bit and the round and sticky bits.
2481                     //
2482                     // Round to nearest even rounding table, adapted from
2483                     // table 4.7 in "Computer Arithmetic" by IsraelKoren.
2484                     // The digit to the left of the "decimal" point is the
2485                     // least significant bit, the digits to the right of
2486                     // the point are the round and sticky bits
2487                     //
2488                     // Number       Round(x)
2489                     // x0.00        x0.
2490                     // x0.01        x0.
2491                     // x0.10        x0.
2492                     // x0.11        x1. = x0. +1
2493                     // x1.00        x1.
2494                     // x1.01        x1.
2495                     // x1.10        x1. + 1
2496                     // x1.11        x1. + 1
2497                     //
2498                     boolean leastZero = ((significand & 1L) == 0L);
2499                     if ((leastZero && round && sticky) ||
2500                             ((!leastZero) && round)) {
2501                         significand++;
2502                     }
2503 
2504                     double value = isNegative ?
2505                             Double.longBitsToDouble(significand | DoubleConsts.SIGN_BIT_MASK) :
2506                             Double.longBitsToDouble(significand );
2507 
2508                     return new PreparedASCIIToBinaryBuffer(value, fValue);
2509                 }
2510             }
2511     }
2512 
2513     /**
2514      * Returns <code>s</code> with any leading zeros removed.
2515      */
stripLeadingZeros(String s)2516     static String stripLeadingZeros(String s) {
2517 //        return  s.replaceFirst("^0+", "");
2518         if(!s.isEmpty() && s.charAt(0)=='0') {
2519             for(int i=1; i<s.length(); i++) {
2520                 if(s.charAt(i)!='0') {
2521                     return s.substring(i);
2522                 }
2523             }
2524             return "";
2525         }
2526         return s;
2527     }
2528 
2529     /**
2530      * Extracts a hexadecimal digit from position <code>position</code>
2531      * of string <code>s</code>.
2532      */
getHexDigit(String s, int position)2533     static int getHexDigit(String s, int position) {
2534         int value = Character.digit(s.charAt(position), 16);
2535         if (value <= -1 || value >= 16) {
2536             throw new AssertionError("Unexpected failure of digit conversion of " +
2537                                      s.charAt(position));
2538         }
2539         return value;
2540     }
2541 }
2542