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