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