1 /* 2 * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 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 }