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