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