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