src/java.base/share/classes/java/lang/Long.java

Print this page




  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 java.lang;
  27 
  28 import java.lang.annotation.Native;
  29 import java.math.*;
  30 import java.util.Objects;
  31 import jdk.internal.HotSpotIntrinsicCandidate;
  32 



  33 
  34 /**
  35  * The {@code Long} class wraps a value of the primitive type {@code
  36  * long} in an object. An object of type {@code Long} contains a
  37  * single field whose type is {@code long}.
  38  *
  39  * <p> In addition, this class provides several methods for converting
  40  * a {@code long} to a {@code String} and a {@code String} to a {@code
  41  * long}, as well as other constants and methods useful when dealing
  42  * with a {@code long}.
  43  *
  44  * <p>Implementation note: The implementations of the "bit twiddling"
  45  * methods (such as {@link #highestOneBit(long) highestOneBit} and
  46  * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are
  47  * based on material from Henry S. Warren, Jr.'s <i>Hacker's
  48  * Delight</i>, (Addison Wesley, 2002).
  49  *
  50  * @author  Lee Boynton
  51  * @author  Arthur van Hoff
  52  * @author  Josh Bloch


 107      * the digits for hexadecimal (radix 16) are
 108      * {@code 0123456789abcdef}. If uppercase letters are
 109      * desired, the {@link java.lang.String#toUpperCase()} method may
 110      * be called on the result:
 111      *
 112      * <blockquote>
 113      *  {@code Long.toString(n, 16).toUpperCase()}
 114      * </blockquote>
 115      *
 116      * @param   i       a {@code long} to be converted to a string.
 117      * @param   radix   the radix to use in the string representation.
 118      * @return  a string representation of the argument in the specified radix.
 119      * @see     java.lang.Character#MAX_RADIX
 120      * @see     java.lang.Character#MIN_RADIX
 121      */
 122     public static String toString(long i, int radix) {
 123         if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
 124             radix = 10;
 125         if (radix == 10)
 126             return toString(i);
 127         char[] buf = new char[65];


 128         int charPos = 64;
 129         boolean negative = (i < 0);
 130 
 131         if (!negative) {
 132             i = -i;
 133         }
 134 
 135         while (i <= -radix) {
 136             buf[charPos--] = Integer.digits[(int)(-(i % radix))];
 137             i = i / radix;
 138         }
 139         buf[charPos] = Integer.digits[(int)(-i)];
 140 
 141         if (negative) {
 142             buf[--charPos] = '-';
 143         }




 144 
 145         return new String(buf, charPos, (65 - charPos));















 146     }
 147 
 148     /**
 149      * Returns a string representation of the first argument as an
 150      * unsigned integer value in the radix specified by the second
 151      * argument.
 152      *
 153      * <p>If the radix is smaller than {@code Character.MIN_RADIX}
 154      * or larger than {@code Character.MAX_RADIX}, then the radix
 155      * {@code 10} is used instead.
 156      *
 157      * <p>Note that since the first argument is treated as an unsigned
 158      * value, no leading sign character is printed.
 159      *
 160      * <p>If the magnitude is zero, it is represented by a single zero
 161      * character {@code '0'} ({@code '\u005Cu0030'}); otherwise,
 162      * the first character of the representation of the magnitude will
 163      * not be the zero character.
 164      *
 165      * <p>The behavior of radixes and the characters used as digits


 338      * @param   i   a {@code long} to be converted to a string.
 339      * @return  the string representation of the unsigned {@code long}
 340      *          value represented by the argument in binary (base&nbsp;2).
 341      * @see #parseUnsignedLong(String, int)
 342      * @see #toUnsignedString(long, int)
 343      * @since   1.0.2
 344      */
 345     public static String toBinaryString(long i) {
 346         return toUnsignedString0(i, 1);
 347     }
 348 
 349     /**
 350      * Format a long (treated as unsigned) into a String.
 351      * @param val the value to format
 352      * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
 353      */
 354     static String toUnsignedString0(long val, int shift) {
 355         // assert shift > 0 && shift <=5 : "Illegal shift value";
 356         int mag = Long.SIZE - Long.numberOfLeadingZeros(val);
 357         int chars = Math.max(((mag + (shift - 1)) / shift), 1);
 358         char[] buf = new char[chars];
 359 
 360         formatUnsignedLong(val, shift, buf, 0, chars);
 361         return new String(buf, true);







 362     }
 363 
 364     /**
 365      * Format a long (treated as unsigned) into a character buffer. If
 366      * {@code len} exceeds the formatted ASCII representation of {@code val},
 367      * {@code buf} will be padded with leading zeroes.
 368      *
 369      * @param val the unsigned long to format
 370      * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
 371      * @param buf the character buffer to write to
 372      * @param offset the offset in the destination buffer to start at
 373      * @param len the number of characters to write
 374      */
 375      static void formatUnsignedLong(long val, int shift, char[] buf, int offset, int len) {
 376         // assert shift > 0 && shift <=5 : "Illegal shift value";
 377         // assert offset >= 0 && offset < buf.length : "illegal offset";
 378         // assert len > 0 && (offset + len) <= buf.length : "illegal length";
 379         int charPos = offset + len;
 380         int radix = 1 << shift;
 381         int mask = radix - 1;
 382         do {
 383             buf[--charPos] = Integer.digits[((int) val) & mask];
 384             val >>>= shift;
 385         } while (charPos > offset);
 386     }
 387 






















 388     /**
 389      * Returns a {@code String} object representing the specified
 390      * {@code long}.  The argument is converted to signed decimal
 391      * representation and returned as a string, exactly as if the
 392      * argument and the radix 10 were given as arguments to the {@link
 393      * #toString(long, int)} method.
 394      *
 395      * @param   i   a {@code long} to be converted.
 396      * @return  a string representation of the argument in base&nbsp;10.
 397      */
 398     public static String toString(long i) {
 399         if (i == Long.MIN_VALUE)
 400             return "-9223372036854775808";
 401         int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
 402         char[] buf = new char[size];

 403         getChars(i, size, buf);
 404         return new String(buf, true);





 405     }
 406 
 407     /**
 408      * Returns a string representation of the argument as an unsigned
 409      * decimal value.
 410      *
 411      * The argument is converted to unsigned decimal representation
 412      * and returned as a string exactly as if the argument and radix
 413      * 10 were given as arguments to the {@link #toUnsignedString(long,
 414      * int)} method.
 415      *
 416      * @param   i  an integer to be converted to an unsigned string.
 417      * @return  an unsigned string representation of the argument.
 418      * @see     #toUnsignedString(long, int)
 419      * @since 1.8
 420      */
 421     public static String toUnsignedString(long i) {
 422         return toUnsignedString(i, 10);
 423     }
 424 
 425     /**
 426      * Places characters representing the integer i into the
 427      * character array buf. The characters are placed into
 428      * the buffer backwards starting with the least significant
 429      * digit at the specified index (exclusive), and working
 430      * backwards from there.
 431      *
 432      * Will fail if i == Long.MIN_VALUE
 433      */
 434     static void getChars(long i, int index, char[] buf) {















































 435         long q;
 436         int r;
 437         int charPos = index;
 438         char sign = 0;
 439 
 440         if (i < 0) {
 441             sign = '-';
 442             i = -i;
 443         }
 444 
 445         // Get 2 digits/iteration using longs until quotient fits into an int
 446         while (i > Integer.MAX_VALUE) {
 447             q = i / 100;
 448             // really: r = i - (q * 100);
 449             r = (int)(i - ((q << 6) + (q << 5) + (q << 2)));
 450             i = q;
 451             buf[--charPos] = Integer.DigitOnes[r];
 452             buf[--charPos] = Integer.DigitTens[r];
 453         }
 454 
 455         // Get 2 digits/iteration using ints
 456         int q2;
 457         int i2 = (int)i;
 458         while (i2 >= 65536) {
 459             q2 = i2 / 100;
 460             // really: r = i2 - (q * 100);
 461             r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
 462             i2 = q2;
 463             buf[--charPos] = Integer.DigitOnes[r];
 464             buf[--charPos] = Integer.DigitTens[r];
 465         }
 466 
 467         // Fall thru to fast mode for smaller numbers
 468         // assert(i2 <= 65536, i2);
 469         for (;;) {
 470             q2 = (i2 * 52429) >>> (16+3);
 471             r = i2 - ((q2 << 3) + (q2 << 1));  // r = i2-(q2*10) ...
 472             buf[--charPos] = Integer.digits[r];
 473             i2 = q2;
 474             if (i2 == 0) break;
 475         }
 476         if (sign != 0) {
 477             buf[--charPos] = sign;
 478         }
 479     }
 480 
 481     // Requires positive x
 482     static int stringSize(long x) {
 483         long p = 10;
 484         for (int i=1; i<19; i++) {
 485             if (x < p)
 486                 return i;
 487             p = 10*p;
 488         }
 489         return 19;
 490     }
 491 
 492     /**
 493      * Parses the string argument as a signed {@code long} in the
 494      * radix specified by the second argument. The characters in the
 495      * string must all be digits of the specified radix (as determined
 496      * by whether {@link java.lang.Character#digit(char, int)} returns
 497      * a nonnegative value), except that the first character may be an




  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 java.lang;
  27 
  28 import java.lang.annotation.Native;
  29 import java.math.*;
  30 import java.util.Objects;
  31 import jdk.internal.HotSpotIntrinsicCandidate;
  32 
  33 import static java.lang.String.COMPACT_STRINGS;
  34 import static java.lang.String.LATIN1;
  35 import static java.lang.String.UTF16;
  36 
  37 /**
  38  * The {@code Long} class wraps a value of the primitive type {@code
  39  * long} in an object. An object of type {@code Long} contains a
  40  * single field whose type is {@code long}.
  41  *
  42  * <p> In addition, this class provides several methods for converting
  43  * a {@code long} to a {@code String} and a {@code String} to a {@code
  44  * long}, as well as other constants and methods useful when dealing
  45  * with a {@code long}.
  46  *
  47  * <p>Implementation note: The implementations of the "bit twiddling"
  48  * methods (such as {@link #highestOneBit(long) highestOneBit} and
  49  * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are
  50  * based on material from Henry S. Warren, Jr.'s <i>Hacker's
  51  * Delight</i>, (Addison Wesley, 2002).
  52  *
  53  * @author  Lee Boynton
  54  * @author  Arthur van Hoff
  55  * @author  Josh Bloch


 110      * the digits for hexadecimal (radix 16) are
 111      * {@code 0123456789abcdef}. If uppercase letters are
 112      * desired, the {@link java.lang.String#toUpperCase()} method may
 113      * be called on the result:
 114      *
 115      * <blockquote>
 116      *  {@code Long.toString(n, 16).toUpperCase()}
 117      * </blockquote>
 118      *
 119      * @param   i       a {@code long} to be converted to a string.
 120      * @param   radix   the radix to use in the string representation.
 121      * @return  a string representation of the argument in the specified radix.
 122      * @see     java.lang.Character#MAX_RADIX
 123      * @see     java.lang.Character#MIN_RADIX
 124      */
 125     public static String toString(long i, int radix) {
 126         if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
 127             radix = 10;
 128         if (radix == 10)
 129             return toString(i);
 130 
 131         if (COMPACT_STRINGS) {
 132             byte[] buf = new byte[65];
 133             int charPos = 64;
 134             boolean negative = (i < 0);
 135 
 136             if (!negative) {
 137                 i = -i;
 138             }
 139 
 140             while (i <= -radix) {
 141                 buf[charPos--] = (byte)Integer.digits[(int)(-(i % radix))];
 142                 i = i / radix;
 143             }
 144             buf[charPos] = (byte)Integer.digits[(int)(-i)];
 145 
 146             if (negative) {
 147                 buf[--charPos] = '-';
 148             }
 149             return StringLatin1.newString(buf, charPos, (65 - charPos));
 150         }
 151         return toStringUTF16(i, radix);
 152     }
 153 
 154     private static String toStringUTF16(long i, int radix) {
 155         byte[] buf = new byte[65 * 2];
 156         int charPos = 64;
 157         boolean negative = (i < 0);
 158         if (!negative) {
 159             i = -i;
 160         }
 161         while (i <= -radix) {
 162             StringUTF16.putChar(buf, charPos--, Integer.digits[(int)(-(i % radix))]);
 163             i = i / radix;
 164         }
 165         StringUTF16.putChar(buf, charPos, Integer.digits[(int)(-i)]);
 166         if (negative) {
 167             StringUTF16.putChar(buf, --charPos, '-');
 168         }
 169         return StringUTF16.newString(buf, charPos, (65 - charPos));
 170     }
 171 
 172     /**
 173      * Returns a string representation of the first argument as an
 174      * unsigned integer value in the radix specified by the second
 175      * argument.
 176      *
 177      * <p>If the radix is smaller than {@code Character.MIN_RADIX}
 178      * or larger than {@code Character.MAX_RADIX}, then the radix
 179      * {@code 10} is used instead.
 180      *
 181      * <p>Note that since the first argument is treated as an unsigned
 182      * value, no leading sign character is printed.
 183      *
 184      * <p>If the magnitude is zero, it is represented by a single zero
 185      * character {@code '0'} ({@code '\u005Cu0030'}); otherwise,
 186      * the first character of the representation of the magnitude will
 187      * not be the zero character.
 188      *
 189      * <p>The behavior of radixes and the characters used as digits


 362      * @param   i   a {@code long} to be converted to a string.
 363      * @return  the string representation of the unsigned {@code long}
 364      *          value represented by the argument in binary (base&nbsp;2).
 365      * @see #parseUnsignedLong(String, int)
 366      * @see #toUnsignedString(long, int)
 367      * @since   1.0.2
 368      */
 369     public static String toBinaryString(long i) {
 370         return toUnsignedString0(i, 1);
 371     }
 372 
 373     /**
 374      * Format a long (treated as unsigned) into a String.
 375      * @param val the value to format
 376      * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
 377      */
 378     static String toUnsignedString0(long val, int shift) {
 379         // assert shift > 0 && shift <=5 : "Illegal shift value";
 380         int mag = Long.SIZE - Long.numberOfLeadingZeros(val);
 381         int chars = Math.max(((mag + (shift - 1)) / shift), 1);

 382 
 383         if (COMPACT_STRINGS) {
 384             byte[] buf = new byte[chars];
 385             formatUnsignedLong0(val, shift, buf, 0, chars);
 386             return new String(buf, LATIN1);
 387         } else {
 388             byte[] buf = new byte[chars * 2];
 389             formatUnsignedLong0UTF16(val, shift, buf, 0, chars);
 390             return new String(buf, UTF16);
 391         }
 392     }
 393 
 394     /**
 395      * Format a long (treated as unsigned) into a character buffer. If
 396      * {@code len} exceeds the formatted ASCII representation of {@code val},
 397      * {@code buf} will be padded with leading zeroes.
 398      *
 399      * @param val the unsigned long to format
 400      * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
 401      * @param buf the character buffer to write to
 402      * @param offset the offset in the destination buffer to start at
 403      * @param len the number of characters to write
 404      */
 405      static void formatUnsignedLong(long val, int shift, char[] buf, int offset, int len) {
 406         // assert shift > 0 && shift <=5 : "Illegal shift value";
 407         // assert offset >= 0 && offset < buf.length : "illegal offset";
 408         // assert len > 0 && (offset + len) <= buf.length : "illegal length";
 409         int charPos = offset + len;
 410         int radix = 1 << shift;
 411         int mask = radix - 1;
 412         do {
 413             buf[--charPos] = Integer.digits[((int) val) & mask];
 414             val >>>= shift;
 415         } while (charPos > offset);
 416     }
 417 
 418     /** byte[]/LATIN1 version    */
 419     static void formatUnsignedLong0(long val, int shift, byte[] buf, int offset, int len) {
 420         int charPos = offset + len;
 421         int radix = 1 << shift;
 422         int mask = radix - 1;
 423         do {
 424             buf[--charPos] = (byte)Integer.digits[((int) val) & mask];
 425             val >>>= shift;
 426         } while (charPos > offset);
 427     }
 428 
 429     /** byte[]/UTF16 version    */
 430     static void formatUnsignedLong0UTF16(long val, int shift, byte[] buf, int offset, int len) {
 431         int charPos = offset + len;
 432         int radix = 1 << shift;
 433         int mask = radix - 1;
 434         do {
 435             StringUTF16.putChar(buf, --charPos, Integer.digits[((int) val) & mask]);
 436             val >>>= shift;
 437         } while (charPos > offset);
 438     }
 439 
 440     /**
 441      * Returns a {@code String} object representing the specified
 442      * {@code long}.  The argument is converted to signed decimal
 443      * representation and returned as a string, exactly as if the
 444      * argument and the radix 10 were given as arguments to the {@link
 445      * #toString(long, int)} method.
 446      *
 447      * @param   i   a {@code long} to be converted.
 448      * @return  a string representation of the argument in base&nbsp;10.
 449      */
 450     public static String toString(long i) {
 451         if (i == Long.MIN_VALUE)
 452             return "-9223372036854775808";
 453         int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
 454         if (COMPACT_STRINGS) {
 455             byte[] buf = new byte[size];
 456             getChars(i, size, buf);
 457             return new String(buf, LATIN1);
 458         } else {
 459             byte[] buf = new byte[size * 2];
 460             getCharsUTF16(i, size, buf);
 461             return new String(buf, UTF16);
 462         }
 463     }
 464 
 465     /**
 466      * Returns a string representation of the argument as an unsigned
 467      * decimal value.
 468      *
 469      * The argument is converted to unsigned decimal representation
 470      * and returned as a string exactly as if the argument and radix
 471      * 10 were given as arguments to the {@link #toUnsignedString(long,
 472      * int)} method.
 473      *
 474      * @param   i  an integer to be converted to an unsigned string.
 475      * @return  an unsigned string representation of the argument.
 476      * @see     #toUnsignedString(long, int)
 477      * @since 1.8
 478      */
 479     public static String toUnsignedString(long i) {
 480         return toUnsignedString(i, 10);
 481     }
 482 
 483     /**
 484      * Places characters representing the integer i into the
 485      * character array buf. The characters are placed into
 486      * the buffer backwards starting with the least significant
 487      * digit at the specified index (exclusive), and working
 488      * backwards from there.
 489      *
 490      * Will fail if i == Long.MIN_VALUE
 491      */
 492     static void getChars(long i, int index, byte[] buf) {
 493         long q;
 494         int r;
 495         int charPos = index;
 496         char sign = 0;
 497 
 498         if (i < 0) {
 499             sign = '-';
 500             i = -i;
 501         }
 502 
 503         // Get 2 digits/iteration using longs until quotient fits into an int
 504         while (i > Integer.MAX_VALUE) {
 505             q = i / 100;
 506             // really: r = i - (q * 100);
 507             r = (int)(i - ((q << 6) + (q << 5) + (q << 2)));
 508             i = q;
 509             buf[--charPos] = (byte)Integer.DigitOnes[r];
 510             buf[--charPos] = (byte)Integer.DigitTens[r];
 511         }
 512 
 513         // Get 2 digits/iteration using ints
 514         int q2;
 515         int i2 = (int)i;
 516         while (i2 >= 65536) {
 517             q2 = i2 / 100;
 518             // really: r = i2 - (q * 100);
 519             r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
 520             i2 = q2;
 521             buf[--charPos] = (byte)Integer.DigitOnes[r];
 522             buf[--charPos] = (byte)Integer.DigitTens[r];
 523         }
 524 
 525         // Fall thru to fast mode for smaller numbers
 526         // assert(i2 <= 65536, i2);
 527         for (;;) {
 528             q2 = (i2 * 52429) >>> (16+3);
 529             r = i2 - ((q2 << 3) + (q2 << 1));  // r = i2-(q2*10) ...
 530             buf[--charPos] = (byte)Integer.digits[r];
 531             i2 = q2;
 532             if (i2 == 0) break;
 533         }
 534         if (sign != 0) {
 535             buf[--charPos] = (byte)sign;
 536         }
 537     }
 538 
 539     static void getCharsUTF16(long i, int index, byte[] buf) {
 540         long q;
 541         int r;
 542         int charPos = index;
 543         char sign = 0;
 544 
 545         if (i < 0) {
 546             sign = '-';
 547             i = -i;
 548         }
 549 
 550         // Get 2 digits/iteration using longs until quotient fits into an int
 551         while (i > Integer.MAX_VALUE) {
 552             q = i / 100;
 553             // really: r = i - (q * 100);
 554             r = (int)(i - ((q << 6) + (q << 5) + (q << 2)));
 555             i = q;
 556             StringUTF16.putChar(buf, --charPos, Integer.DigitOnes[r]);
 557             StringUTF16.putChar(buf, --charPos, Integer.DigitTens[r]);
 558         }
 559 
 560         // Get 2 digits/iteration using ints
 561         int q2;
 562         int i2 = (int)i;
 563         while (i2 >= 65536) {
 564             q2 = i2 / 100;
 565             // really: r = i2 - (q * 100);
 566             r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
 567             i2 = q2;
 568             StringUTF16.putChar(buf, --charPos, Integer.DigitOnes[r]);
 569             StringUTF16.putChar(buf, --charPos, Integer.DigitTens[r]);
 570         }
 571 
 572         // Fall thru to fast mode for smaller numbers
 573         // assert(i2 <= 65536, i2);
 574         for (;;) {
 575             q2 = (i2 * 52429) >>> (16+3);
 576             r = i2 - ((q2 << 3) + (q2 << 1));  // r = i2-(q2*10) ...
 577             StringUTF16.putChar(buf, --charPos, Integer.digits[r]);
 578             i2 = q2;
 579             if (i2 == 0) break;
 580         }
 581         if (sign != 0) {
 582             StringUTF16.putChar(buf, --charPos, sign);
 583         }
 584     }
 585 
 586     // Requires positive x
 587     static int stringSize(long x) {
 588         long p = 10;
 589         for (int i=1; i<19; i++) {
 590             if (x < p)
 591                 return i;
 592             p = 10*p;
 593         }
 594         return 19;
 595     }
 596 
 597     /**
 598      * Parses the string argument as a signed {@code long} in the
 599      * radix specified by the second argument. The characters in the
 600      * string must all be digits of the specified radix (as determined
 601      * by whether {@link java.lang.Character#digit(char, int)} returns
 602      * a nonnegative value), except that the first character may be an