1 /* 2 * Copyright (c) 1994, 2021, 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 java.lang; 27 28 import java.lang.annotation.Native; 29 30 import java.lang.invoke.MethodHandles; 31 import java.lang.constant.Constable; 32 import java.lang.constant.ConstantDesc; 33 import java.util.Optional; 34 35 import java.math.*; 36 import java.util.Objects; 37 38 // Android-removed: CDS is not used on Android. 39 // import jdk.internal.misc.CDS; 40 41 import jdk.internal.vm.annotation.IntrinsicCandidate; 42 43 44 /** 45 * The {@code Long} class wraps a value of the primitive type {@code 46 * long} in an object. An object of type {@code Long} contains a 47 * single field whose type is {@code long}. 48 * 49 * <p> In addition, this class provides several methods for converting 50 * a {@code long} to a {@code String} and a {@code String} to a {@code 51 * long}, as well as other constants and methods useful when dealing 52 * with a {@code long}. 53 * 54 * <!-- Android-removed: paragraph on ValueBased 55 * <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a> 56 * class; programmers should treat instances that are 57 * {@linkplain #equals(Object) equal} as interchangeable and should not 58 * use instances for synchronization, or unpredictable behavior may 59 * occur. For example, in a future release, synchronization may fail. 60 * --> 61 * 62 * <p>Implementation note: The implementations of the "bit twiddling" 63 * methods (such as {@link #highestOneBit(long) highestOneBit} and 64 * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are 65 * based on material from Henry S. Warren, Jr.'s <i>Hacker's 66 * Delight</i>, (Addison Wesley, 2002). 67 * 68 * @author Lee Boynton 69 * @author Arthur van Hoff 70 * @author Josh Bloch 71 * @author Joseph D. Darcy 72 * @since 1.0 73 */ 74 @jdk.internal.ValueBased 75 public final class Long extends Number 76 implements Comparable<Long>, Constable, ConstantDesc { 77 /** 78 * A constant holding the minimum value a {@code long} can 79 * have, -2<sup>63</sup>. 80 */ 81 @Native public static final long MIN_VALUE = 0x8000000000000000L; 82 83 /** 84 * A constant holding the maximum value a {@code long} can 85 * have, 2<sup>63</sup>-1. 86 */ 87 @Native public static final long MAX_VALUE = 0x7fffffffffffffffL; 88 89 /** 90 * The {@code Class} instance representing the primitive type 91 * {@code long}. 92 * 93 * @since 1.1 94 */ 95 @SuppressWarnings("unchecked") 96 public static final Class<Long> TYPE = (Class<Long>) Class.getPrimitiveClass("long"); 97 98 /** 99 * Returns a string representation of the first argument in the 100 * radix specified by the second argument. 101 * 102 * <p>If the radix is smaller than {@code Character.MIN_RADIX} 103 * or larger than {@code Character.MAX_RADIX}, then the radix 104 * {@code 10} is used instead. 105 * 106 * <p>If the first argument is negative, the first element of the 107 * result is the ASCII minus sign {@code '-'} 108 * ({@code '\u005Cu002d'}). If the first argument is not 109 * negative, no sign character appears in the result. 110 * 111 * <p>The remaining characters of the result represent the magnitude 112 * of the first argument. If the magnitude is zero, it is 113 * represented by a single zero character {@code '0'} 114 * ({@code '\u005Cu0030'}); otherwise, the first character of 115 * the representation of the magnitude will not be the zero 116 * character. The following ASCII characters are used as digits: 117 * 118 * <blockquote> 119 * {@code 0123456789abcdefghijklmnopqrstuvwxyz} 120 * </blockquote> 121 * 122 * These are {@code '\u005Cu0030'} through 123 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through 124 * {@code '\u005Cu007a'}. If {@code radix} is 125 * <var>N</var>, then the first <var>N</var> of these characters 126 * are used as radix-<var>N</var> digits in the order shown. Thus, 127 * the digits for hexadecimal (radix 16) are 128 * {@code 0123456789abcdef}. If uppercase letters are 129 * desired, the {@link java.lang.String#toUpperCase()} method may 130 * be called on the result: 131 * 132 * <blockquote> 133 * {@code Long.toString(n, 16).toUpperCase()} 134 * </blockquote> 135 * 136 * @param i a {@code long} to be converted to a string. 137 * @param radix the radix to use in the string representation. 138 * @return a string representation of the argument in the specified radix. 139 * @see java.lang.Character#MAX_RADIX 140 * @see java.lang.Character#MIN_RADIX 141 */ toString(long i, int radix)142 public static String toString(long i, int radix) { 143 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) 144 radix = 10; 145 if (radix == 10) 146 return toString(i); 147 148 // BEGIN Android-changed: Use single-byte chars. 149 /* 150 if (COMPACT_STRINGS) { 151 */ 152 byte[] buf = new byte[65]; 153 int charPos = 64; 154 boolean negative = (i < 0); 155 156 if (!negative) { 157 i = -i; 158 } 159 160 while (i <= -radix) { 161 buf[charPos--] = (byte)Integer.digits[(int)(-(i % radix))]; 162 i = i / radix; 163 } 164 buf[charPos] = (byte)Integer.digits[(int)(-i)]; 165 166 if (negative) { 167 buf[--charPos] = '-'; 168 } 169 /* 170 return StringLatin1.newString(buf, charPos, (65 - charPos)); 171 } 172 return toStringUTF16(i, radix); 173 */ 174 return new String(buf, charPos, (65 - charPos)); 175 // END Android-changed: Use single-byte chars. 176 } 177 178 // BEGIN Android-removed: UTF16 version of toString(long i, int radix). 179 /* 180 private static String toStringUTF16(long i, int radix) { 181 byte[] buf = new byte[65 * 2]; 182 int charPos = 64; 183 boolean negative = (i < 0); 184 if (!negative) { 185 i = -i; 186 } 187 while (i <= -radix) { 188 StringUTF16.putChar(buf, charPos--, Integer.digits[(int)(-(i % radix))]); 189 i = i / radix; 190 } 191 StringUTF16.putChar(buf, charPos, Integer.digits[(int)(-i)]); 192 if (negative) { 193 StringUTF16.putChar(buf, --charPos, '-'); 194 } 195 return StringUTF16.newString(buf, charPos, (65 - charPos)); 196 } 197 */ 198 // END Android-removed: UTF16 version of toString(long i, int radix). 199 200 /** 201 * Returns a string representation of the first argument as an 202 * unsigned integer value in the radix specified by the second 203 * argument. 204 * 205 * <p>If the radix is smaller than {@code Character.MIN_RADIX} 206 * or larger than {@code Character.MAX_RADIX}, then the radix 207 * {@code 10} is used instead. 208 * 209 * <p>Note that since the first argument is treated as an unsigned 210 * value, no leading sign character is printed. 211 * 212 * <p>If the magnitude is zero, it is represented by a single zero 213 * character {@code '0'} ({@code '\u005Cu0030'}); otherwise, 214 * the first character of the representation of the magnitude will 215 * not be the zero character. 216 * 217 * <p>The behavior of radixes and the characters used as digits 218 * are the same as {@link #toString(long, int) toString}. 219 * 220 * @param i an integer to be converted to an unsigned string. 221 * @param radix the radix to use in the string representation. 222 * @return an unsigned string representation of the argument in the specified radix. 223 * @see #toString(long, int) 224 * @since 1.8 225 */ toUnsignedString(long i, int radix)226 public static String toUnsignedString(long i, int radix) { 227 if (i >= 0) 228 return toString(i, radix); 229 else { 230 return switch (radix) { 231 case 2 -> toBinaryString(i); 232 case 4 -> toUnsignedString0(i, 2); 233 case 8 -> toOctalString(i); 234 case 10 -> { 235 /* 236 * We can get the effect of an unsigned division by 10 237 * on a long value by first shifting right, yielding a 238 * positive value, and then dividing by 5. This 239 * allows the last digit and preceding digits to be 240 * isolated more quickly than by an initial conversion 241 * to BigInteger. 242 */ 243 long quot = (i >>> 1) / 5; 244 long rem = i - quot * 10; 245 yield toString(quot) + rem; 246 } 247 case 16 -> toHexString(i); 248 case 32 -> toUnsignedString0(i, 5); 249 default -> toUnsignedBigInteger(i).toString(radix); 250 }; 251 } 252 } 253 254 /** 255 * Return a BigInteger equal to the unsigned value of the 256 * argument. 257 */ toUnsignedBigInteger(long i)258 private static BigInteger toUnsignedBigInteger(long i) { 259 if (i >= 0L) 260 return BigInteger.valueOf(i); 261 else { 262 int upper = (int) (i >>> 32); 263 int lower = (int) i; 264 265 // return (upper << 32) + lower 266 return (BigInteger.valueOf(Integer.toUnsignedLong(upper))).shiftLeft(32). 267 add(BigInteger.valueOf(Integer.toUnsignedLong(lower))); 268 } 269 } 270 271 // Android-removed: java.util.HexFormat references in javadoc as not present. 272 /** 273 * Returns a string representation of the {@code long} 274 * argument as an unsigned integer in base 16. 275 * 276 * <p>The unsigned {@code long} value is the argument plus 277 * 2<sup>64</sup> if the argument is negative; otherwise, it is 278 * equal to the argument. This value is converted to a string of 279 * ASCII digits in hexadecimal (base 16) with no extra 280 * leading {@code 0}s. 281 * 282 * <p>The value of the argument can be recovered from the returned 283 * string {@code s} by calling {@link 284 * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s, 285 * 16)}. 286 * 287 * <p>If the unsigned magnitude is zero, it is represented by a 288 * single zero character {@code '0'} ({@code '\u005Cu0030'}); 289 * otherwise, the first character of the representation of the 290 * unsigned magnitude will not be the zero character. The 291 * following characters are used as hexadecimal digits: 292 * 293 * <blockquote> 294 * {@code 0123456789abcdef} 295 * </blockquote> 296 * 297 * These are the characters {@code '\u005Cu0030'} through 298 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through 299 * {@code '\u005Cu0066'}. If uppercase letters are desired, 300 * the {@link java.lang.String#toUpperCase()} method may be called 301 * on the result: 302 * 303 * <blockquote> 304 * {@code Long.toHexString(n).toUpperCase()} 305 * </blockquote> 306 * 307 * @param i a {@code long} to be converted to a string. 308 * @return the string representation of the unsigned {@code long} 309 * value represented by the argument in hexadecimal 310 * (base 16). 311 * @see #parseUnsignedLong(String, int) 312 * @see #toUnsignedString(long, int) 313 * @since 1.0.2 314 */ toHexString(long i)315 public static String toHexString(long i) { 316 return toUnsignedString0(i, 4); 317 } 318 319 /** 320 * Returns a string representation of the {@code long} 321 * argument as an unsigned integer in base 8. 322 * 323 * <p>The unsigned {@code long} value is the argument plus 324 * 2<sup>64</sup> if the argument is negative; otherwise, it is 325 * equal to the argument. This value is converted to a string of 326 * ASCII digits in octal (base 8) with no extra leading 327 * {@code 0}s. 328 * 329 * <p>The value of the argument can be recovered from the returned 330 * string {@code s} by calling {@link 331 * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s, 332 * 8)}. 333 * 334 * <p>If the unsigned magnitude is zero, it is represented by a 335 * single zero character {@code '0'} ({@code '\u005Cu0030'}); 336 * otherwise, the first character of the representation of the 337 * unsigned magnitude will not be the zero character. The 338 * following characters are used as octal digits: 339 * 340 * <blockquote> 341 * {@code 01234567} 342 * </blockquote> 343 * 344 * These are the characters {@code '\u005Cu0030'} through 345 * {@code '\u005Cu0037'}. 346 * 347 * @param i a {@code long} to be converted to a string. 348 * @return the string representation of the unsigned {@code long} 349 * value represented by the argument in octal (base 8). 350 * @see #parseUnsignedLong(String, int) 351 * @see #toUnsignedString(long, int) 352 * @since 1.0.2 353 */ toOctalString(long i)354 public static String toOctalString(long i) { 355 return toUnsignedString0(i, 3); 356 } 357 358 /** 359 * Returns a string representation of the {@code long} 360 * argument as an unsigned integer in base 2. 361 * 362 * <p>The unsigned {@code long} value is the argument plus 363 * 2<sup>64</sup> if the argument is negative; otherwise, it is 364 * equal to the argument. This value is converted to a string of 365 * ASCII digits in binary (base 2) with no extra leading 366 * {@code 0}s. 367 * 368 * <p>The value of the argument can be recovered from the returned 369 * string {@code s} by calling {@link 370 * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s, 371 * 2)}. 372 * 373 * <p>If the unsigned magnitude is zero, it is represented by a 374 * single zero character {@code '0'} ({@code '\u005Cu0030'}); 375 * otherwise, the first character of the representation of the 376 * unsigned magnitude will not be the zero character. The 377 * characters {@code '0'} ({@code '\u005Cu0030'}) and {@code 378 * '1'} ({@code '\u005Cu0031'}) are used as binary digits. 379 * 380 * @param i a {@code long} to be converted to a string. 381 * @return the string representation of the unsigned {@code long} 382 * value represented by the argument in binary (base 2). 383 * @see #parseUnsignedLong(String, int) 384 * @see #toUnsignedString(long, int) 385 * @since 1.0.2 386 */ toBinaryString(long i)387 public static String toBinaryString(long i) { 388 return toUnsignedString0(i, 1); 389 } 390 391 /** 392 * Format a long (treated as unsigned) into a String. 393 * @param val the value to format 394 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary) 395 */ toUnsignedString0(long val, int shift)396 static String toUnsignedString0(long val, int shift) { 397 // assert shift > 0 && shift <=5 : "Illegal shift value"; 398 int mag = Long.SIZE - Long.numberOfLeadingZeros(val); 399 int chars = Math.max(((mag + (shift - 1)) / shift), 1); 400 401 // BEGIN Android-changed: Use single-byte chars. 402 /* 403 if (COMPACT_STRINGS) { 404 */ 405 byte[] buf = new byte[chars]; 406 formatUnsignedLong0(val, shift, buf, 0, chars); 407 /* 408 return new String(buf, LATIN1); 409 } else { 410 byte[] buf = new byte[chars * 2]; 411 formatUnsignedLong0UTF16(val, shift, buf, 0, chars); 412 return new String(buf, UTF16); 413 } 414 */ 415 return new String(buf); 416 // END Android-changed: Use single-byte chars. 417 } 418 419 /** 420 * Format a long (treated as unsigned) into a byte buffer (LATIN1 version). If 421 * {@code len} exceeds the formatted ASCII representation of {@code val}, 422 * {@code buf} will be padded with leading zeroes. 423 * 424 * @param val the unsigned long to format 425 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary) 426 * @param buf the byte buffer to write to 427 * @param offset the offset in the destination buffer to start at 428 * @param len the number of characters to write 429 */ 430 // Android-changed: dropped private modifier formatUnsignedLong0(long val, int shift, byte[] buf, int offset, int len)431 static void formatUnsignedLong0(long val, int shift, byte[] buf, int offset, int len) { 432 int charPos = offset + len; 433 int radix = 1 << shift; 434 int mask = radix - 1; 435 do { 436 buf[--charPos] = (byte)Integer.digits[((int) val) & mask]; 437 val >>>= shift; 438 } while (charPos > offset); 439 } 440 441 // BEGIN Android-removed: UTF16 version of formatUnsignedLong0(). 442 /* 443 /** byte[]/UTF16 version * 444 private static void formatUnsignedLong0UTF16(long val, int shift, byte[] buf, int offset, int len) { 445 int charPos = offset + len; 446 int radix = 1 << shift; 447 int mask = radix - 1; 448 do { 449 StringUTF16.putChar(buf, --charPos, Integer.digits[((int) val) & mask]); 450 val >>>= shift; 451 } while (charPos > offset); 452 } 453 */ 454 // END Android-removed: UTF16 version of formatUnsignedLong0(). 455 456 /** 457 * Returns a {@code String} object representing the specified 458 * {@code long}. The argument is converted to signed decimal 459 * representation and returned as a string, exactly as if the 460 * argument and the radix 10 were given as arguments to the {@link 461 * #toString(long, int)} method. 462 * 463 * @param i a {@code long} to be converted. 464 * @return a string representation of the argument in base 10. 465 */ toString(long i)466 public static String toString(long i) { 467 int size = stringSize(i); 468 // BEGIN Android-changed: Always use single-byte buffer. 469 /* 470 if (COMPACT_STRINGS) { 471 */ 472 byte[] buf = new byte[size]; 473 getChars(i, size, buf); 474 /* 475 return new String(buf, LATIN1); 476 } else { 477 byte[] buf = new byte[size * 2]; 478 StringUTF16.getChars(i, size, buf); 479 return new String(buf, UTF16); 480 } 481 */ 482 return new String(buf); 483 // END Android-changed: Always use single-byte buffer. 484 } 485 486 /** 487 * Returns a string representation of the argument as an unsigned 488 * decimal value. 489 * 490 * The argument is converted to unsigned decimal representation 491 * and returned as a string exactly as if the argument and radix 492 * 10 were given as arguments to the {@link #toUnsignedString(long, 493 * int)} method. 494 * 495 * @param i an integer to be converted to an unsigned string. 496 * @return an unsigned string representation of the argument. 497 * @see #toUnsignedString(long, int) 498 * @since 1.8 499 */ toUnsignedString(long i)500 public static String toUnsignedString(long i) { 501 return toUnsignedString(i, 10); 502 } 503 504 /** 505 * Places characters representing the long i into the 506 * character array buf. The characters are placed into 507 * the buffer backwards starting with the least significant 508 * digit at the specified index (exclusive), and working 509 * backwards from there. 510 * 511 * @implNote This method converts positive inputs into negative 512 * values, to cover the Long.MIN_VALUE case. Converting otherwise 513 * (negative to positive) will expose -Long.MIN_VALUE that overflows 514 * long. 515 * 516 * @param i value to convert 517 * @param index next index, after the least significant digit 518 * @param buf target buffer, Latin1-encoded 519 * @return index of the most significant digit or minus sign, if present 520 */ getChars(long i, int index, byte[] buf)521 static int getChars(long i, int index, byte[] buf) { 522 long q; 523 int r; 524 int charPos = index; 525 526 boolean negative = (i < 0); 527 if (!negative) { 528 i = -i; 529 } 530 531 // Get 2 digits/iteration using longs until quotient fits into an int 532 while (i <= Integer.MIN_VALUE) { 533 q = i / 100; 534 r = (int)((q * 100) - i); 535 i = q; 536 buf[--charPos] = Integer.DigitOnes[r]; 537 buf[--charPos] = Integer.DigitTens[r]; 538 } 539 540 // Get 2 digits/iteration using ints 541 int q2; 542 int i2 = (int)i; 543 while (i2 <= -100) { 544 q2 = i2 / 100; 545 r = (q2 * 100) - i2; 546 i2 = q2; 547 buf[--charPos] = Integer.DigitOnes[r]; 548 buf[--charPos] = Integer.DigitTens[r]; 549 } 550 551 // We know there are at most two digits left at this point. 552 q2 = i2 / 10; 553 r = (q2 * 10) - i2; 554 buf[--charPos] = (byte)('0' + r); 555 556 // Whatever left is the remaining digit. 557 if (q2 < 0) { 558 buf[--charPos] = (byte)('0' - q2); 559 } 560 561 if (negative) { 562 buf[--charPos] = (byte)'-'; 563 } 564 return charPos; 565 } 566 567 // BEGIN Android-added: char version of getChars(long i, int index, byte[] buf). 568 // for java.lang.AbstractStringBuilder#append(int). getChars(long i, int index, char[] buf)569 static int getChars(long i, int index, char[] buf) { 570 long q; 571 int r; 572 int charPos = index; 573 574 boolean negative = (i < 0); 575 if (!negative) { 576 i = -i; 577 } 578 579 // Get 2 digits/iteration using longs until quotient fits into an int 580 while (i <= Integer.MIN_VALUE) { 581 q = i / 100; 582 r = (int)((q * 100) - i); 583 i = q; 584 buf[--charPos] = (char)Integer.DigitOnes[r]; 585 buf[--charPos] = (char)Integer.DigitTens[r]; 586 } 587 588 // Get 2 digits/iteration using ints 589 int q2; 590 int i2 = (int)i; 591 while (i2 <= -100) { 592 q2 = i2 / 100; 593 r = (q2 * 100) - i2; 594 i2 = q2; 595 buf[--charPos] = (char)Integer.DigitOnes[r]; 596 buf[--charPos] = (char)Integer.DigitTens[r]; 597 } 598 599 // We know there are at most two digits left at this point. 600 q2 = i2 / 10; 601 r = (q2 * 10) - i2; 602 buf[--charPos] = (char)('0' + r); 603 604 // Whatever left is the remaining digit. 605 if (q2 < 0) { 606 buf[--charPos] = (char)('0' - q2); 607 } 608 609 if (negative) { 610 buf[--charPos] = (byte)'-'; 611 } 612 return charPos; 613 } 614 // END Android-added: char version of getChars(long i, int index, byte[] buf). 615 616 /** 617 * Returns the string representation size for a given long value. 618 * 619 * @param x long value 620 * @return string size 621 * 622 * @implNote There are other ways to compute this: e.g. binary search, 623 * but values are biased heavily towards zero, and therefore linear search 624 * wins. The iteration results are also routinely inlined in the generated 625 * code after loop unrolling. 626 */ stringSize(long x)627 static int stringSize(long x) { 628 int d = 1; 629 if (x >= 0) { 630 d = 0; 631 x = -x; 632 } 633 long p = -10; 634 for (int i = 1; i < 19; i++) { 635 if (x > p) 636 return i + d; 637 p = 10 * p; 638 } 639 return 19 + d; 640 } 641 642 /** 643 * Parses the string argument as a signed {@code long} in the 644 * radix specified by the second argument. The characters in the 645 * string must all be digits of the specified radix (as determined 646 * by whether {@link java.lang.Character#digit(char, int)} returns 647 * a nonnegative value), except that the first character may be an 648 * ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to 649 * indicate a negative value or an ASCII plus sign {@code '+'} 650 * ({@code '\u005Cu002B'}) to indicate a positive value. The 651 * resulting {@code long} value is returned. 652 * 653 * <p>Note that neither the character {@code L} 654 * ({@code '\u005Cu004C'}) nor {@code l} 655 * ({@code '\u005Cu006C'}) is permitted to appear at the end 656 * of the string as a type indicator, as would be permitted in 657 * Java programming language source code - except that either 658 * {@code L} or {@code l} may appear as a digit for a 659 * radix greater than or equal to 22. 660 * 661 * <p>An exception of type {@code NumberFormatException} is 662 * thrown if any of the following situations occurs: 663 * <ul> 664 * 665 * <li>The first argument is {@code null} or is a string of 666 * length zero. 667 * 668 * <li>The {@code radix} is either smaller than {@link 669 * java.lang.Character#MIN_RADIX} or larger than {@link 670 * java.lang.Character#MAX_RADIX}. 671 * 672 * <li>Any character of the string is not a digit of the specified 673 * radix, except that the first character may be a minus sign 674 * {@code '-'} ({@code '\u005Cu002d'}) or plus sign {@code 675 * '+'} ({@code '\u005Cu002B'}) provided that the string is 676 * longer than length 1. 677 * 678 * <li>The value represented by the string is not a value of type 679 * {@code long}. 680 * </ul> 681 * 682 * <p>Examples: 683 * <blockquote><pre> 684 * parseLong("0", 10) returns 0L 685 * parseLong("473", 10) returns 473L 686 * parseLong("+42", 10) returns 42L 687 * parseLong("-0", 10) returns 0L 688 * parseLong("-FF", 16) returns -255L 689 * parseLong("1100110", 2) returns 102L 690 * parseLong("99", 8) throws a NumberFormatException 691 * parseLong("Hazelnut", 10) throws a NumberFormatException 692 * parseLong("Hazelnut", 36) returns 1356099454469L 693 * </pre></blockquote> 694 * 695 * @param s the {@code String} containing the 696 * {@code long} representation to be parsed. 697 * @param radix the radix to be used while parsing {@code s}. 698 * @return the {@code long} represented by the string argument in 699 * the specified radix. 700 * @throws NumberFormatException if the string does not contain a 701 * parsable {@code long}. 702 */ parseLong(String s, int radix)703 public static long parseLong(String s, int radix) 704 throws NumberFormatException 705 { 706 if (s == null) { 707 throw new NumberFormatException("Cannot parse null string"); 708 } 709 710 if (radix < Character.MIN_RADIX) { 711 throw new NumberFormatException("radix " + radix + 712 " less than Character.MIN_RADIX"); 713 } 714 if (radix > Character.MAX_RADIX) { 715 throw new NumberFormatException("radix " + radix + 716 " greater than Character.MAX_RADIX"); 717 } 718 719 boolean negative = false; 720 int i = 0, len = s.length(); 721 long limit = -Long.MAX_VALUE; 722 723 if (len > 0) { 724 char firstChar = s.charAt(0); 725 if (firstChar < '0') { // Possible leading "+" or "-" 726 if (firstChar == '-') { 727 negative = true; 728 limit = Long.MIN_VALUE; 729 } else if (firstChar != '+') { 730 throw NumberFormatException.forInputString(s, radix); 731 } 732 733 if (len == 1) { // Cannot have lone "+" or "-" 734 throw NumberFormatException.forInputString(s, radix); 735 } 736 i++; 737 } 738 long multmin = limit / radix; 739 long result = 0; 740 while (i < len) { 741 // Accumulating negatively avoids surprises near MAX_VALUE 742 int digit = Character.digit(s.charAt(i++),radix); 743 if (digit < 0 || result < multmin) { 744 throw NumberFormatException.forInputString(s, radix); 745 } 746 result *= radix; 747 if (result < limit + digit) { 748 throw NumberFormatException.forInputString(s, radix); 749 } 750 result -= digit; 751 } 752 return negative ? result : -result; 753 } else { 754 throw NumberFormatException.forInputString(s, radix); 755 } 756 } 757 758 /** 759 * Parses the {@link CharSequence} argument as a signed {@code long} in 760 * the specified {@code radix}, beginning at the specified 761 * {@code beginIndex} and extending to {@code endIndex - 1}. 762 * 763 * <p>The method does not take steps to guard against the 764 * {@code CharSequence} being mutated while parsing. 765 * 766 * @param s the {@code CharSequence} containing the {@code long} 767 * representation to be parsed 768 * @param beginIndex the beginning index, inclusive. 769 * @param endIndex the ending index, exclusive. 770 * @param radix the radix to be used while parsing {@code s}. 771 * @return the signed {@code long} represented by the subsequence in 772 * the specified radix. 773 * @throws NullPointerException if {@code s} is null. 774 * @throws IndexOutOfBoundsException if {@code beginIndex} is 775 * negative, or if {@code beginIndex} is greater than 776 * {@code endIndex} or if {@code endIndex} is greater than 777 * {@code s.length()}. 778 * @throws NumberFormatException if the {@code CharSequence} does not 779 * contain a parsable {@code long} in the specified 780 * {@code radix}, or if {@code radix} is either smaller than 781 * {@link java.lang.Character#MIN_RADIX} or larger than 782 * {@link java.lang.Character#MAX_RADIX}. 783 * @since 9 784 */ parseLong(CharSequence s, int beginIndex, int endIndex, int radix)785 public static long parseLong(CharSequence s, int beginIndex, int endIndex, int radix) 786 throws NumberFormatException { 787 Objects.requireNonNull(s); 788 789 if (beginIndex < 0 || beginIndex > endIndex || endIndex > s.length()) { 790 throw new IndexOutOfBoundsException(); 791 } 792 if (radix < Character.MIN_RADIX) { 793 throw new NumberFormatException("radix " + radix + 794 " less than Character.MIN_RADIX"); 795 } 796 if (radix > Character.MAX_RADIX) { 797 throw new NumberFormatException("radix " + radix + 798 " greater than Character.MAX_RADIX"); 799 } 800 801 boolean negative = false; 802 int i = beginIndex; 803 long limit = -Long.MAX_VALUE; 804 805 if (i < endIndex) { 806 char firstChar = s.charAt(i); 807 if (firstChar < '0') { // Possible leading "+" or "-" 808 if (firstChar == '-') { 809 negative = true; 810 limit = Long.MIN_VALUE; 811 } else if (firstChar != '+') { 812 throw NumberFormatException.forCharSequence(s, beginIndex, 813 endIndex, i); 814 } 815 i++; 816 } 817 if (i >= endIndex) { // Cannot have lone "+", "-" or "" 818 throw NumberFormatException.forCharSequence(s, beginIndex, 819 endIndex, i); 820 } 821 long multmin = limit / radix; 822 long result = 0; 823 while (i < endIndex) { 824 // Accumulating negatively avoids surprises near MAX_VALUE 825 int digit = Character.digit(s.charAt(i), radix); 826 if (digit < 0 || result < multmin) { 827 throw NumberFormatException.forCharSequence(s, beginIndex, 828 endIndex, i); 829 } 830 result *= radix; 831 if (result < limit + digit) { 832 throw NumberFormatException.forCharSequence(s, beginIndex, 833 endIndex, i); 834 } 835 i++; 836 result -= digit; 837 } 838 return negative ? result : -result; 839 } else { 840 throw new NumberFormatException(""); 841 } 842 } 843 844 /** 845 * Parses the string argument as a signed decimal {@code long}. 846 * The characters in the string must all be decimal digits, except 847 * that the first character may be an ASCII minus sign {@code '-'} 848 * ({@code \u005Cu002D'}) to indicate a negative value or an 849 * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to 850 * indicate a positive value. The resulting {@code long} value is 851 * returned, exactly as if the argument and the radix {@code 10} 852 * were given as arguments to the {@link 853 * #parseLong(java.lang.String, int)} method. 854 * 855 * <p>Note that neither the character {@code L} 856 * ({@code '\u005Cu004C'}) nor {@code l} 857 * ({@code '\u005Cu006C'}) is permitted to appear at the end 858 * of the string as a type indicator, as would be permitted in 859 * Java programming language source code. 860 * 861 * @param s a {@code String} containing the {@code long} 862 * representation to be parsed 863 * @return the {@code long} represented by the argument in 864 * decimal. 865 * @throws NumberFormatException if the string does not contain a 866 * parsable {@code long}. 867 */ parseLong(String s)868 public static long parseLong(String s) throws NumberFormatException { 869 return parseLong(s, 10); 870 } 871 872 /** 873 * Parses the string argument as an unsigned {@code long} in the 874 * radix specified by the second argument. An unsigned integer 875 * maps the values usually associated with negative numbers to 876 * positive numbers larger than {@code MAX_VALUE}. 877 * 878 * The characters in the string must all be digits of the 879 * specified radix (as determined by whether {@link 880 * java.lang.Character#digit(char, int)} returns a nonnegative 881 * value), except that the first character may be an ASCII plus 882 * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting 883 * integer value is returned. 884 * 885 * <p>An exception of type {@code NumberFormatException} is 886 * thrown if any of the following situations occurs: 887 * <ul> 888 * <li>The first argument is {@code null} or is a string of 889 * length zero. 890 * 891 * <li>The radix is either smaller than 892 * {@link java.lang.Character#MIN_RADIX} or 893 * larger than {@link java.lang.Character#MAX_RADIX}. 894 * 895 * <li>Any character of the string is not a digit of the specified 896 * radix, except that the first character may be a plus sign 897 * {@code '+'} ({@code '\u005Cu002B'}) provided that the 898 * string is longer than length 1. 899 * 900 * <li>The value represented by the string is larger than the 901 * largest unsigned {@code long}, 2<sup>64</sup>-1. 902 * 903 * </ul> 904 * 905 * 906 * @param s the {@code String} containing the unsigned integer 907 * representation to be parsed 908 * @param radix the radix to be used while parsing {@code s}. 909 * @return the unsigned {@code long} represented by the string 910 * argument in the specified radix. 911 * @throws NumberFormatException if the {@code String} 912 * does not contain a parsable {@code long}. 913 * @since 1.8 914 */ parseUnsignedLong(String s, int radix)915 public static long parseUnsignedLong(String s, int radix) 916 throws NumberFormatException { 917 if (s == null) { 918 throw new NumberFormatException("Cannot parse null string"); 919 } 920 921 int len = s.length(); 922 if (len > 0) { 923 char firstChar = s.charAt(0); 924 if (firstChar == '-') { 925 throw new 926 NumberFormatException(String.format("Illegal leading minus sign " + 927 "on unsigned string %s.", s)); 928 } else { 929 if (len <= 12 || // Long.MAX_VALUE in Character.MAX_RADIX is 13 digits 930 (radix == 10 && len <= 18) ) { // Long.MAX_VALUE in base 10 is 19 digits 931 return parseLong(s, radix); 932 } 933 934 // No need for range checks on len due to testing above. 935 long first = parseLong(s, 0, len - 1, radix); 936 int second = Character.digit(s.charAt(len - 1), radix); 937 if (second < 0) { 938 throw new NumberFormatException("Bad digit at end of " + s); 939 } 940 long result = first * radix + second; 941 942 /* 943 * Test leftmost bits of multiprecision extension of first*radix 944 * for overflow. The number of bits needed is defined by 945 * GUARD_BIT = ceil(log2(Character.MAX_RADIX)) + 1 = 7. Then 946 * int guard = radix*(int)(first >>> (64 - GUARD_BIT)) and 947 * overflow is tested by splitting guard in the ranges 948 * guard < 92, 92 <= guard < 128, and 128 <= guard, where 949 * 92 = 128 - Character.MAX_RADIX. Note that guard cannot take 950 * on a value which does not include a prime factor in the legal 951 * radix range. 952 */ 953 int guard = radix * (int) (first >>> 57); 954 if (guard >= 128 || 955 (result >= 0 && guard >= 128 - Character.MAX_RADIX)) { 956 /* 957 * For purposes of exposition, the programmatic statements 958 * below should be taken to be multi-precision, i.e., not 959 * subject to overflow. 960 * 961 * A) Condition guard >= 128: 962 * If guard >= 128 then first*radix >= 2^7 * 2^57 = 2^64 963 * hence always overflow. 964 * 965 * B) Condition guard < 92: 966 * Define left7 = first >>> 57. 967 * Given first = (left7 * 2^57) + (first & (2^57 - 1)) then 968 * result <= (radix*left7)*2^57 + radix*(2^57 - 1) + second. 969 * Thus if radix*left7 < 92, radix <= 36, and second < 36, 970 * then result < 92*2^57 + 36*(2^57 - 1) + 36 = 2^64 hence 971 * never overflow. 972 * 973 * C) Condition 92 <= guard < 128: 974 * first*radix + second >= radix*left7*2^57 + second 975 * so that first*radix + second >= 92*2^57 + 0 > 2^63 976 * 977 * D) Condition guard < 128: 978 * radix*first <= (radix*left7) * 2^57 + radix*(2^57 - 1) 979 * so 980 * radix*first + second <= (radix*left7) * 2^57 + radix*(2^57 - 1) + 36 981 * thus 982 * radix*first + second < 128 * 2^57 + 36*2^57 - radix + 36 983 * whence 984 * radix*first + second < 2^64 + 2^6*2^57 = 2^64 + 2^63 985 * 986 * E) Conditions C, D, and result >= 0: 987 * C and D combined imply the mathematical result 988 * 2^63 < first*radix + second < 2^64 + 2^63. The lower 989 * bound is therefore negative as a signed long, but the 990 * upper bound is too small to overflow again after the 991 * signed long overflows to positive above 2^64 - 1. Hence 992 * result >= 0 implies overflow given C and D. 993 */ 994 throw new NumberFormatException(String.format("String value %s exceeds " + 995 "range of unsigned long.", s)); 996 } 997 return result; 998 } 999 } else { 1000 throw NumberFormatException.forInputString(s, radix); 1001 } 1002 } 1003 1004 /** 1005 * Parses the {@link CharSequence} argument as an unsigned {@code long} in 1006 * the specified {@code radix}, beginning at the specified 1007 * {@code beginIndex} and extending to {@code endIndex - 1}. 1008 * 1009 * <p>The method does not take steps to guard against the 1010 * {@code CharSequence} being mutated while parsing. 1011 * 1012 * @param s the {@code CharSequence} containing the unsigned 1013 * {@code long} representation to be parsed 1014 * @param beginIndex the beginning index, inclusive. 1015 * @param endIndex the ending index, exclusive. 1016 * @param radix the radix to be used while parsing {@code s}. 1017 * @return the unsigned {@code long} represented by the subsequence in 1018 * the specified radix. 1019 * @throws NullPointerException if {@code s} is null. 1020 * @throws IndexOutOfBoundsException if {@code beginIndex} is 1021 * negative, or if {@code beginIndex} is greater than 1022 * {@code endIndex} or if {@code endIndex} is greater than 1023 * {@code s.length()}. 1024 * @throws NumberFormatException if the {@code CharSequence} does not 1025 * contain a parsable unsigned {@code long} in the specified 1026 * {@code radix}, or if {@code radix} is either smaller than 1027 * {@link java.lang.Character#MIN_RADIX} or larger than 1028 * {@link java.lang.Character#MAX_RADIX}. 1029 * @since 9 1030 */ parseUnsignedLong(CharSequence s, int beginIndex, int endIndex, int radix)1031 public static long parseUnsignedLong(CharSequence s, int beginIndex, int endIndex, int radix) 1032 throws NumberFormatException { 1033 Objects.requireNonNull(s); 1034 1035 if (beginIndex < 0 || beginIndex > endIndex || endIndex > s.length()) { 1036 throw new IndexOutOfBoundsException(); 1037 } 1038 int start = beginIndex, len = endIndex - beginIndex; 1039 1040 if (len > 0) { 1041 char firstChar = s.charAt(start); 1042 if (firstChar == '-') { 1043 throw new NumberFormatException(String.format("Illegal leading minus sign " + 1044 "on unsigned string %s.", s.subSequence(start, start + len))); 1045 } else { 1046 if (len <= 12 || // Long.MAX_VALUE in Character.MAX_RADIX is 13 digits 1047 (radix == 10 && len <= 18) ) { // Long.MAX_VALUE in base 10 is 19 digits 1048 return parseLong(s, start, start + len, radix); 1049 } 1050 1051 // No need for range checks on end due to testing above. 1052 long first = parseLong(s, start, start + len - 1, radix); 1053 int second = Character.digit(s.charAt(start + len - 1), radix); 1054 if (second < 0) { 1055 throw new NumberFormatException("Bad digit at end of " + 1056 s.subSequence(start, start + len)); 1057 } 1058 long result = first * radix + second; 1059 1060 /* 1061 * Test leftmost bits of multiprecision extension of first*radix 1062 * for overflow. The number of bits needed is defined by 1063 * GUARD_BIT = ceil(log2(Character.MAX_RADIX)) + 1 = 7. Then 1064 * int guard = radix*(int)(first >>> (64 - GUARD_BIT)) and 1065 * overflow is tested by splitting guard in the ranges 1066 * guard < 92, 92 <= guard < 128, and 128 <= guard, where 1067 * 92 = 128 - Character.MAX_RADIX. Note that guard cannot take 1068 * on a value which does not include a prime factor in the legal 1069 * radix range. 1070 */ 1071 int guard = radix * (int) (first >>> 57); 1072 if (guard >= 128 || 1073 (result >= 0 && guard >= 128 - Character.MAX_RADIX)) { 1074 /* 1075 * For purposes of exposition, the programmatic statements 1076 * below should be taken to be multi-precision, i.e., not 1077 * subject to overflow. 1078 * 1079 * A) Condition guard >= 128: 1080 * If guard >= 128 then first*radix >= 2^7 * 2^57 = 2^64 1081 * hence always overflow. 1082 * 1083 * B) Condition guard < 92: 1084 * Define left7 = first >>> 57. 1085 * Given first = (left7 * 2^57) + (first & (2^57 - 1)) then 1086 * result <= (radix*left7)*2^57 + radix*(2^57 - 1) + second. 1087 * Thus if radix*left7 < 92, radix <= 36, and second < 36, 1088 * then result < 92*2^57 + 36*(2^57 - 1) + 36 = 2^64 hence 1089 * never overflow. 1090 * 1091 * C) Condition 92 <= guard < 128: 1092 * first*radix + second >= radix*left7*2^57 + second 1093 * so that first*radix + second >= 92*2^57 + 0 > 2^63 1094 * 1095 * D) Condition guard < 128: 1096 * radix*first <= (radix*left7) * 2^57 + radix*(2^57 - 1) 1097 * so 1098 * radix*first + second <= (radix*left7) * 2^57 + radix*(2^57 - 1) + 36 1099 * thus 1100 * radix*first + second < 128 * 2^57 + 36*2^57 - radix + 36 1101 * whence 1102 * radix*first + second < 2^64 + 2^6*2^57 = 2^64 + 2^63 1103 * 1104 * E) Conditions C, D, and result >= 0: 1105 * C and D combined imply the mathematical result 1106 * 2^63 < first*radix + second < 2^64 + 2^63. The lower 1107 * bound is therefore negative as a signed long, but the 1108 * upper bound is too small to overflow again after the 1109 * signed long overflows to positive above 2^64 - 1. Hence 1110 * result >= 0 implies overflow given C and D. 1111 */ 1112 throw new NumberFormatException(String.format("String value %s exceeds " + 1113 "range of unsigned long.", s.subSequence(start, start + len))); 1114 } 1115 return result; 1116 } 1117 } else { 1118 throw NumberFormatException.forInputString("", radix); 1119 } 1120 } 1121 1122 /** 1123 * Parses the string argument as an unsigned decimal {@code long}. The 1124 * characters in the string must all be decimal digits, except 1125 * that the first character may be an ASCII plus sign {@code 1126 * '+'} ({@code '\u005Cu002B'}). The resulting integer value 1127 * is returned, exactly as if the argument and the radix 10 were 1128 * given as arguments to the {@link 1129 * #parseUnsignedLong(java.lang.String, int)} method. 1130 * 1131 * @param s a {@code String} containing the unsigned {@code long} 1132 * representation to be parsed 1133 * @return the unsigned {@code long} value represented by the decimal string argument 1134 * @throws NumberFormatException if the string does not contain a 1135 * parsable unsigned integer. 1136 * @since 1.8 1137 */ parseUnsignedLong(String s)1138 public static long parseUnsignedLong(String s) throws NumberFormatException { 1139 return parseUnsignedLong(s, 10); 1140 } 1141 1142 /** 1143 * Returns a {@code Long} object holding the value 1144 * extracted from the specified {@code String} when parsed 1145 * with the radix given by the second argument. The first 1146 * argument is interpreted as representing a signed 1147 * {@code long} in the radix specified by the second 1148 * argument, exactly as if the arguments were given to the {@link 1149 * #parseLong(java.lang.String, int)} method. The result is a 1150 * {@code Long} object that represents the {@code long} 1151 * value specified by the string. 1152 * 1153 * <p>In other words, this method returns a {@code Long} object equal 1154 * to the value of: 1155 * 1156 * <blockquote> 1157 * {@code new Long(Long.parseLong(s, radix))} 1158 * </blockquote> 1159 * 1160 * @param s the string to be parsed 1161 * @param radix the radix to be used in interpreting {@code s} 1162 * @return a {@code Long} object holding the value 1163 * represented by the string argument in the specified 1164 * radix. 1165 * @throws NumberFormatException If the {@code String} does not 1166 * contain a parsable {@code long}. 1167 */ valueOf(String s, int radix)1168 public static Long valueOf(String s, int radix) throws NumberFormatException { 1169 return Long.valueOf(parseLong(s, radix)); 1170 } 1171 1172 /** 1173 * Returns a {@code Long} object holding the value 1174 * of the specified {@code String}. The argument is 1175 * interpreted as representing a signed decimal {@code long}, 1176 * exactly as if the argument were given to the {@link 1177 * #parseLong(java.lang.String)} method. The result is a 1178 * {@code Long} object that represents the integer value 1179 * specified by the string. 1180 * 1181 * <p>In other words, this method returns a {@code Long} object 1182 * equal to the value of: 1183 * 1184 * <blockquote> 1185 * {@code new Long(Long.parseLong(s))} 1186 * </blockquote> 1187 * 1188 * @param s the string to be parsed. 1189 * @return a {@code Long} object holding the value 1190 * represented by the string argument. 1191 * @throws NumberFormatException If the string cannot be parsed 1192 * as a {@code long}. 1193 */ valueOf(String s)1194 public static Long valueOf(String s) throws NumberFormatException 1195 { 1196 return Long.valueOf(parseLong(s, 10)); 1197 } 1198 1199 private static class LongCache { LongCache()1200 private LongCache() {} 1201 1202 static final Long[] cache; 1203 static Long[] archivedCache; 1204 1205 static { 1206 int size = -(-128) + 127 + 1; 1207 1208 // Load and use the archived cache if it exists 1209 // Android-removed: CDS is not used on Android. 1210 // CDS.initializeFromArchive(LongCache.class); 1211 if (archivedCache == null || archivedCache.length != size) { 1212 Long[] c = new Long[size]; 1213 long value = -128; 1214 for(int i = 0; i < size; i++) { 1215 c[i] = new Long(value++); 1216 } 1217 archivedCache = c; 1218 } 1219 cache = archivedCache; 1220 } 1221 } 1222 1223 /** 1224 * Returns a {@code Long} instance representing the specified 1225 * {@code long} value. 1226 * If a new {@code Long} instance is not required, this method 1227 * should generally be used in preference to the constructor 1228 * {@link #Long(long)}, as this method is likely to yield 1229 * significantly better space and time performance by caching 1230 * frequently requested values. 1231 * 1232 * This method will always cache values in the range -128 to 127, 1233 * inclusive, and may cache other values outside of this range. 1234 * 1235 * @param l a long value. 1236 * @return a {@code Long} instance representing {@code l}. 1237 * @since 1.5 1238 */ 1239 @IntrinsicCandidate valueOf(long l)1240 public static Long valueOf(long l) { 1241 final int offset = 128; 1242 if (l >= -128 && l <= 127) { // will cache 1243 return LongCache.cache[(int)l + offset]; 1244 } 1245 return new Long(l); 1246 } 1247 1248 /** 1249 * Decodes a {@code String} into a {@code Long}. 1250 * Accepts decimal, hexadecimal, and octal numbers given by the 1251 * following grammar: 1252 * 1253 * <blockquote> 1254 * <dl> 1255 * <dt><i>DecodableString:</i> 1256 * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i> 1257 * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i> 1258 * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i> 1259 * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i> 1260 * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i> 1261 * 1262 * <dt><i>Sign:</i> 1263 * <dd>{@code -} 1264 * <dd>{@code +} 1265 * </dl> 1266 * </blockquote> 1267 * 1268 * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i> 1269 * are as defined in section {@jls 3.10.1} of 1270 * <cite>The Java Language Specification</cite>, 1271 * except that underscores are not accepted between digits. 1272 * 1273 * <p>The sequence of characters following an optional 1274 * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", 1275 * "{@code #}", or leading zero) is parsed as by the {@code 1276 * Long.parseLong} method with the indicated radix (10, 16, or 8). 1277 * This sequence of characters must represent a positive value or 1278 * a {@link NumberFormatException} will be thrown. The result is 1279 * negated if first character of the specified {@code String} is 1280 * the minus sign. No whitespace characters are permitted in the 1281 * {@code String}. 1282 * 1283 * @param nm the {@code String} to decode. 1284 * @return a {@code Long} object holding the {@code long} 1285 * value represented by {@code nm} 1286 * @throws NumberFormatException if the {@code String} does not 1287 * contain a parsable {@code long}. 1288 * @see java.lang.Long#parseLong(String, int) 1289 * @since 1.2 1290 */ decode(String nm)1291 public static Long decode(String nm) throws NumberFormatException { 1292 int radix = 10; 1293 int index = 0; 1294 boolean negative = false; 1295 Long result; 1296 1297 if (nm.isEmpty()) 1298 throw new NumberFormatException("Zero length string"); 1299 char firstChar = nm.charAt(0); 1300 // Handle sign, if present 1301 if (firstChar == '-') { 1302 negative = true; 1303 index++; 1304 } else if (firstChar == '+') 1305 index++; 1306 1307 // Handle radix specifier, if present 1308 if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) { 1309 index += 2; 1310 radix = 16; 1311 } 1312 else if (nm.startsWith("#", index)) { 1313 index ++; 1314 radix = 16; 1315 } 1316 else if (nm.startsWith("0", index) && nm.length() > 1 + index) { 1317 index ++; 1318 radix = 8; 1319 } 1320 1321 if (nm.startsWith("-", index) || nm.startsWith("+", index)) 1322 throw new NumberFormatException("Sign character in wrong position"); 1323 1324 try { 1325 result = Long.valueOf(nm.substring(index), radix); 1326 result = negative ? Long.valueOf(-result.longValue()) : result; 1327 } catch (NumberFormatException e) { 1328 // If number is Long.MIN_VALUE, we'll end up here. The next line 1329 // handles this case, and causes any genuine format error to be 1330 // rethrown. 1331 String constant = negative ? ("-" + nm.substring(index)) 1332 : nm.substring(index); 1333 result = Long.valueOf(constant, radix); 1334 } 1335 return result; 1336 } 1337 1338 /** 1339 * The value of the {@code Long}. 1340 * 1341 * @serial 1342 */ 1343 private final long value; 1344 1345 /** 1346 * Constructs a newly allocated {@code Long} object that 1347 * represents the specified {@code long} argument. 1348 * 1349 * @param value the value to be represented by the 1350 * {@code Long} object. 1351 * 1352 * @deprecated 1353 * It is rarely appropriate to use this constructor. The static factory 1354 * {@link #valueOf(long)} is generally a better choice, as it is 1355 * likely to yield significantly better space and time performance. 1356 */ 1357 // Android-changed: not yet forRemoval on Android. 1358 @Deprecated(since="9"/*, forRemoval = true*/) Long(long value)1359 public Long(long value) { 1360 this.value = value; 1361 } 1362 1363 /** 1364 * Constructs a newly allocated {@code Long} object that 1365 * represents the {@code long} value indicated by the 1366 * {@code String} parameter. The string is converted to a 1367 * {@code long} value in exactly the manner used by the 1368 * {@code parseLong} method for radix 10. 1369 * 1370 * @param s the {@code String} to be converted to a 1371 * {@code Long}. 1372 * @throws NumberFormatException if the {@code String} does not 1373 * contain a parsable {@code long}. 1374 * 1375 * @deprecated 1376 * It is rarely appropriate to use this constructor. 1377 * Use {@link #parseLong(String)} to convert a string to a 1378 * {@code long} primitive, or use {@link #valueOf(String)} 1379 * to convert a string to a {@code Long} object. 1380 */ 1381 @Deprecated(since="9"/*, forRemoval = true*/) Long(String s)1382 public Long(String s) throws NumberFormatException { 1383 this.value = parseLong(s, 10); 1384 } 1385 1386 /** 1387 * Returns the value of this {@code Long} as a {@code byte} after 1388 * a narrowing primitive conversion. 1389 * @jls 5.1.3 Narrowing Primitive Conversion 1390 */ byteValue()1391 public byte byteValue() { 1392 return (byte)value; 1393 } 1394 1395 /** 1396 * Returns the value of this {@code Long} as a {@code short} after 1397 * a narrowing primitive conversion. 1398 * @jls 5.1.3 Narrowing Primitive Conversion 1399 */ shortValue()1400 public short shortValue() { 1401 return (short)value; 1402 } 1403 1404 /** 1405 * Returns the value of this {@code Long} as an {@code int} after 1406 * a narrowing primitive conversion. 1407 * @jls 5.1.3 Narrowing Primitive Conversion 1408 */ intValue()1409 public int intValue() { 1410 return (int)value; 1411 } 1412 1413 /** 1414 * Returns the value of this {@code Long} as a 1415 * {@code long} value. 1416 */ 1417 @IntrinsicCandidate longValue()1418 public long longValue() { 1419 return value; 1420 } 1421 1422 /** 1423 * Returns the value of this {@code Long} as a {@code float} after 1424 * a widening primitive conversion. 1425 * @jls 5.1.2 Widening Primitive Conversion 1426 */ floatValue()1427 public float floatValue() { 1428 return (float)value; 1429 } 1430 1431 /** 1432 * Returns the value of this {@code Long} as a {@code double} 1433 * after a widening primitive conversion. 1434 * @jls 5.1.2 Widening Primitive Conversion 1435 */ doubleValue()1436 public double doubleValue() { 1437 return (double)value; 1438 } 1439 1440 /** 1441 * Returns a {@code String} object representing this 1442 * {@code Long}'s value. The value is converted to signed 1443 * decimal representation and returned as a string, exactly as if 1444 * the {@code long} value were given as an argument to the 1445 * {@link java.lang.Long#toString(long)} method. 1446 * 1447 * @return a string representation of the value of this object in 1448 * base 10. 1449 */ toString()1450 public String toString() { 1451 return toString(value); 1452 } 1453 1454 /** 1455 * Returns a hash code for this {@code Long}. The result is 1456 * the exclusive OR of the two halves of the primitive 1457 * {@code long} value held by this {@code Long} 1458 * object. That is, the hashcode is the value of the expression: 1459 * 1460 * <blockquote> 1461 * {@code (int)(this.longValue()^(this.longValue()>>>32))} 1462 * </blockquote> 1463 * 1464 * @return a hash code value for this object. 1465 */ 1466 @Override hashCode()1467 public int hashCode() { 1468 return Long.hashCode(value); 1469 } 1470 1471 /** 1472 * Returns a hash code for a {@code long} value; compatible with 1473 * {@code Long.hashCode()}. 1474 * 1475 * @param value the value to hash 1476 * @return a hash code value for a {@code long} value. 1477 * @since 1.8 1478 */ hashCode(long value)1479 public static int hashCode(long value) { 1480 return (int)(value ^ (value >>> 32)); 1481 } 1482 1483 /** 1484 * Compares this object to the specified object. The result is 1485 * {@code true} if and only if the argument is not 1486 * {@code null} and is a {@code Long} object that 1487 * contains the same {@code long} value as this object. 1488 * 1489 * @param obj the object to compare with. 1490 * @return {@code true} if the objects are the same; 1491 * {@code false} otherwise. 1492 */ equals(Object obj)1493 public boolean equals(Object obj) { 1494 if (obj instanceof Long) { 1495 return value == ((Long)obj).longValue(); 1496 } 1497 return false; 1498 } 1499 1500 /** 1501 * Determines the {@code long} value of the system property 1502 * with the specified name. 1503 * 1504 * <p>The first argument is treated as the name of a system 1505 * property. System properties are accessible through the {@link 1506 * java.lang.System#getProperty(java.lang.String)} method. The 1507 * string value of this property is then interpreted as a {@code 1508 * long} value using the grammar supported by {@link Long#decode decode} 1509 * and a {@code Long} object representing this value is returned. 1510 * 1511 * <p>If there is no property with the specified name, if the 1512 * specified name is empty or {@code null}, or if the property 1513 * does not have the correct numeric format, then {@code null} is 1514 * returned. 1515 * 1516 * <p>In other words, this method returns a {@code Long} object 1517 * equal to the value of: 1518 * 1519 * <blockquote> 1520 * {@code getLong(nm, null)} 1521 * </blockquote> 1522 * 1523 * @param nm property name. 1524 * @return the {@code Long} value of the property. 1525 * @throws SecurityException for the same reasons as 1526 * {@link System#getProperty(String) System.getProperty} 1527 * @see java.lang.System#getProperty(java.lang.String) 1528 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1529 */ getLong(String nm)1530 public static Long getLong(String nm) { 1531 return getLong(nm, null); 1532 } 1533 1534 /** 1535 * Determines the {@code long} value of the system property 1536 * with the specified name. 1537 * 1538 * <p>The first argument is treated as the name of a system 1539 * property. System properties are accessible through the {@link 1540 * java.lang.System#getProperty(java.lang.String)} method. The 1541 * string value of this property is then interpreted as a {@code 1542 * long} value using the grammar supported by {@link Long#decode decode} 1543 * and a {@code Long} object representing this value is returned. 1544 * 1545 * <p>The second argument is the default value. A {@code Long} object 1546 * that represents the value of the second argument is returned if there 1547 * is no property of the specified name, if the property does not have 1548 * the correct numeric format, or if the specified name is empty or null. 1549 * 1550 * <p>In other words, this method returns a {@code Long} object equal 1551 * to the value of: 1552 * 1553 * <blockquote> 1554 * {@code getLong(nm, new Long(val))} 1555 * </blockquote> 1556 * 1557 * but in practice it may be implemented in a manner such as: 1558 * 1559 * <blockquote><pre> 1560 * Long result = getLong(nm, null); 1561 * return (result == null) ? new Long(val) : result; 1562 * </pre></blockquote> 1563 * 1564 * to avoid the unnecessary allocation of a {@code Long} object when 1565 * the default value is not needed. 1566 * 1567 * @param nm property name. 1568 * @param val default value. 1569 * @return the {@code Long} value of the property. 1570 * @throws SecurityException for the same reasons as 1571 * {@link System#getProperty(String) System.getProperty} 1572 * @see java.lang.System#getProperty(java.lang.String) 1573 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1574 */ getLong(String nm, long val)1575 public static Long getLong(String nm, long val) { 1576 Long result = Long.getLong(nm, null); 1577 return (result == null) ? Long.valueOf(val) : result; 1578 } 1579 1580 /** 1581 * Returns the {@code long} value of the system property with 1582 * the specified name. The first argument is treated as the name 1583 * of a system property. System properties are accessible through 1584 * the {@link java.lang.System#getProperty(java.lang.String)} 1585 * method. The string value of this property is then interpreted 1586 * as a {@code long} value, as per the 1587 * {@link Long#decode decode} method, and a {@code Long} object 1588 * representing this value is returned; in summary: 1589 * 1590 * <ul> 1591 * <li>If the property value begins with the two ASCII characters 1592 * {@code 0x} or the ASCII character {@code #}, not followed by 1593 * a minus sign, then the rest of it is parsed as a hexadecimal integer 1594 * exactly as for the method {@link #valueOf(java.lang.String, int)} 1595 * with radix 16. 1596 * <li>If the property value begins with the ASCII character 1597 * {@code 0} followed by another character, it is parsed as 1598 * an octal integer exactly as by the method {@link 1599 * #valueOf(java.lang.String, int)} with radix 8. 1600 * <li>Otherwise the property value is parsed as a decimal 1601 * integer exactly as by the method 1602 * {@link #valueOf(java.lang.String, int)} with radix 10. 1603 * </ul> 1604 * 1605 * <p>Note that, in every case, neither {@code L} 1606 * ({@code '\u005Cu004C'}) nor {@code l} 1607 * ({@code '\u005Cu006C'}) is permitted to appear at the end 1608 * of the property value as a type indicator, as would be 1609 * permitted in Java programming language source code. 1610 * 1611 * <p>The second argument is the default value. The default value is 1612 * returned if there is no property of the specified name, if the 1613 * property does not have the correct numeric format, or if the 1614 * specified name is empty or {@code null}. 1615 * 1616 * @param nm property name. 1617 * @param val default value. 1618 * @return the {@code Long} value of the property. 1619 * @throws SecurityException for the same reasons as 1620 * {@link System#getProperty(String) System.getProperty} 1621 * @see System#getProperty(java.lang.String) 1622 * @see System#getProperty(java.lang.String, java.lang.String) 1623 */ getLong(String nm, Long val)1624 public static Long getLong(String nm, Long val) { 1625 String v = null; 1626 try { 1627 v = System.getProperty(nm); 1628 } catch (IllegalArgumentException | NullPointerException e) { 1629 } 1630 if (v != null) { 1631 try { 1632 return Long.decode(v); 1633 } catch (NumberFormatException e) { 1634 } 1635 } 1636 return val; 1637 } 1638 1639 /** 1640 * Compares two {@code Long} objects numerically. 1641 * 1642 * @param anotherLong the {@code Long} to be compared. 1643 * @return the value {@code 0} if this {@code Long} is 1644 * equal to the argument {@code Long}; a value less than 1645 * {@code 0} if this {@code Long} is numerically less 1646 * than the argument {@code Long}; and a value greater 1647 * than {@code 0} if this {@code Long} is numerically 1648 * greater than the argument {@code Long} (signed 1649 * comparison). 1650 * @since 1.2 1651 */ compareTo(Long anotherLong)1652 public int compareTo(Long anotherLong) { 1653 return compare(this.value, anotherLong.value); 1654 } 1655 1656 /** 1657 * Compares two {@code long} values numerically. 1658 * The value returned is identical to what would be returned by: 1659 * <pre> 1660 * Long.valueOf(x).compareTo(Long.valueOf(y)) 1661 * </pre> 1662 * 1663 * @param x the first {@code long} to compare 1664 * @param y the second {@code long} to compare 1665 * @return the value {@code 0} if {@code x == y}; 1666 * a value less than {@code 0} if {@code x < y}; and 1667 * a value greater than {@code 0} if {@code x > y} 1668 * @since 1.7 1669 */ compare(long x, long y)1670 public static int compare(long x, long y) { 1671 return (x < y) ? -1 : ((x == y) ? 0 : 1); 1672 } 1673 1674 /** 1675 * Compares two {@code long} values numerically treating the values 1676 * as unsigned. 1677 * 1678 * @param x the first {@code long} to compare 1679 * @param y the second {@code long} to compare 1680 * @return the value {@code 0} if {@code x == y}; a value less 1681 * than {@code 0} if {@code x < y} as unsigned values; and 1682 * a value greater than {@code 0} if {@code x > y} as 1683 * unsigned values 1684 * @since 1.8 1685 */ compareUnsigned(long x, long y)1686 public static int compareUnsigned(long x, long y) { 1687 return compare(x + MIN_VALUE, y + MIN_VALUE); 1688 } 1689 1690 1691 /** 1692 * Returns the unsigned quotient of dividing the first argument by 1693 * the second where each argument and the result is interpreted as 1694 * an unsigned value. 1695 * 1696 * <p>Note that in two's complement arithmetic, the three other 1697 * basic arithmetic operations of add, subtract, and multiply are 1698 * bit-wise identical if the two operands are regarded as both 1699 * being signed or both being unsigned. Therefore separate {@code 1700 * addUnsigned}, etc. methods are not provided. 1701 * 1702 * @param dividend the value to be divided 1703 * @param divisor the value doing the dividing 1704 * @return the unsigned quotient of the first argument divided by 1705 * the second argument 1706 * @see #remainderUnsigned 1707 * @since 1.8 1708 */ divideUnsigned(long dividend, long divisor)1709 public static long divideUnsigned(long dividend, long divisor) { 1710 /* See Hacker's Delight (2nd ed), section 9.3 */ 1711 if (divisor >= 0) { 1712 final long q = (dividend >>> 1) / divisor << 1; 1713 final long r = dividend - q * divisor; 1714 return q + ((r | ~(r - divisor)) >>> (Long.SIZE - 1)); 1715 } 1716 return (dividend & ~(dividend - divisor)) >>> (Long.SIZE - 1); 1717 } 1718 1719 /** 1720 * Returns the unsigned remainder from dividing the first argument 1721 * by the second where each argument and the result is interpreted 1722 * as an unsigned value. 1723 * 1724 * @param dividend the value to be divided 1725 * @param divisor the value doing the dividing 1726 * @return the unsigned remainder of the first argument divided by 1727 * the second argument 1728 * @see #divideUnsigned 1729 * @since 1.8 1730 */ remainderUnsigned(long dividend, long divisor)1731 public static long remainderUnsigned(long dividend, long divisor) { 1732 /* See Hacker's Delight (2nd ed), section 9.3 */ 1733 if (divisor >= 0) { 1734 final long q = (dividend >>> 1) / divisor << 1; 1735 final long r = dividend - q * divisor; 1736 /* 1737 * Here, 0 <= r < 2 * divisor 1738 * (1) When 0 <= r < divisor, the remainder is simply r. 1739 * (2) Otherwise the remainder is r - divisor. 1740 * 1741 * In case (1), r - divisor < 0. Applying ~ produces a long with 1742 * sign bit 0, so >> produces 0. The returned value is thus r. 1743 * 1744 * In case (2), a similar reasoning shows that >> produces -1, 1745 * so the returned value is r - divisor. 1746 */ 1747 return r - ((~(r - divisor) >> (Long.SIZE - 1)) & divisor); 1748 } 1749 /* 1750 * (1) When dividend >= 0, the remainder is dividend. 1751 * (2) Otherwise 1752 * (2.1) When dividend < divisor, the remainder is dividend. 1753 * (2.2) Otherwise the remainder is dividend - divisor 1754 * 1755 * A reasoning similar to the above shows that the returned value 1756 * is as expected. 1757 */ 1758 return dividend - (((dividend & ~(dividend - divisor)) >> (Long.SIZE - 1)) & divisor); 1759 } 1760 1761 // Bit Twiddling 1762 1763 /** 1764 * The number of bits used to represent a {@code long} value in two's 1765 * complement binary form. 1766 * 1767 * @since 1.5 1768 */ 1769 @Native public static final int SIZE = 64; 1770 1771 /** 1772 * The number of bytes used to represent a {@code long} value in two's 1773 * complement binary form. 1774 * 1775 * @since 1.8 1776 */ 1777 public static final int BYTES = SIZE / Byte.SIZE; 1778 1779 /** 1780 * Returns a {@code long} value with at most a single one-bit, in the 1781 * position of the highest-order ("leftmost") one-bit in the specified 1782 * {@code long} value. Returns zero if the specified value has no 1783 * one-bits in its two's complement binary representation, that is, if it 1784 * is equal to zero. 1785 * 1786 * @param i the value whose highest one bit is to be computed 1787 * @return a {@code long} value with a single one-bit, in the position 1788 * of the highest-order one-bit in the specified value, or zero if 1789 * the specified value is itself equal to zero. 1790 * @since 1.5 1791 */ highestOneBit(long i)1792 public static long highestOneBit(long i) { 1793 return i & (MIN_VALUE >>> numberOfLeadingZeros(i)); 1794 } 1795 1796 /** 1797 * Returns a {@code long} value with at most a single one-bit, in the 1798 * position of the lowest-order ("rightmost") one-bit in the specified 1799 * {@code long} value. Returns zero if the specified value has no 1800 * one-bits in its two's complement binary representation, that is, if it 1801 * is equal to zero. 1802 * 1803 * @param i the value whose lowest one bit is to be computed 1804 * @return a {@code long} value with a single one-bit, in the position 1805 * of the lowest-order one-bit in the specified value, or zero if 1806 * the specified value is itself equal to zero. 1807 * @since 1.5 1808 */ lowestOneBit(long i)1809 public static long lowestOneBit(long i) { 1810 // HD, Section 2-1 1811 return i & -i; 1812 } 1813 1814 /** 1815 * Returns the number of zero bits preceding the highest-order 1816 * ("leftmost") one-bit in the two's complement binary representation 1817 * of the specified {@code long} value. Returns 64 if the 1818 * specified value has no one-bits in its two's complement representation, 1819 * in other words if it is equal to zero. 1820 * 1821 * <p>Note that this method is closely related to the logarithm base 2. 1822 * For all positive {@code long} values x: 1823 * <ul> 1824 * <li>floor(log<sub>2</sub>(x)) = {@code 63 - numberOfLeadingZeros(x)} 1825 * <li>ceil(log<sub>2</sub>(x)) = {@code 64 - numberOfLeadingZeros(x - 1)} 1826 * </ul> 1827 * 1828 * @param i the value whose number of leading zeros is to be computed 1829 * @return the number of zero bits preceding the highest-order 1830 * ("leftmost") one-bit in the two's complement binary representation 1831 * of the specified {@code long} value, or 64 if the value 1832 * is equal to zero. 1833 * @since 1.5 1834 */ 1835 @IntrinsicCandidate numberOfLeadingZeros(long i)1836 public static int numberOfLeadingZeros(long i) { 1837 int x = (int)(i >>> 32); 1838 return x == 0 ? 32 + Integer.numberOfLeadingZeros((int)i) 1839 : Integer.numberOfLeadingZeros(x); 1840 } 1841 1842 /** 1843 * Returns the number of zero bits following the lowest-order ("rightmost") 1844 * one-bit in the two's complement binary representation of the specified 1845 * {@code long} value. Returns 64 if the specified value has no 1846 * one-bits in its two's complement representation, in other words if it is 1847 * equal to zero. 1848 * 1849 * @param i the value whose number of trailing zeros is to be computed 1850 * @return the number of zero bits following the lowest-order ("rightmost") 1851 * one-bit in the two's complement binary representation of the 1852 * specified {@code long} value, or 64 if the value is equal 1853 * to zero. 1854 * @since 1.5 1855 */ 1856 @IntrinsicCandidate numberOfTrailingZeros(long i)1857 public static int numberOfTrailingZeros(long i) { 1858 int x = (int)i; 1859 return x == 0 ? 32 + Integer.numberOfTrailingZeros((int)(i >>> 32)) 1860 : Integer.numberOfTrailingZeros(x); 1861 } 1862 1863 /** 1864 * Returns the number of one-bits in the two's complement binary 1865 * representation of the specified {@code long} value. This function is 1866 * sometimes referred to as the <i>population count</i>. 1867 * 1868 * @param i the value whose bits are to be counted 1869 * @return the number of one-bits in the two's complement binary 1870 * representation of the specified {@code long} value. 1871 * @since 1.5 1872 */ 1873 @IntrinsicCandidate bitCount(long i)1874 public static int bitCount(long i) { 1875 // HD, Figure 5-2 1876 i = i - ((i >>> 1) & 0x5555555555555555L); 1877 i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L); 1878 i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL; 1879 i = i + (i >>> 8); 1880 i = i + (i >>> 16); 1881 i = i + (i >>> 32); 1882 return (int)i & 0x7f; 1883 } 1884 1885 /** 1886 * Returns the value obtained by rotating the two's complement binary 1887 * representation of the specified {@code long} value left by the 1888 * specified number of bits. (Bits shifted out of the left hand, or 1889 * high-order, side reenter on the right, or low-order.) 1890 * 1891 * <p>Note that left rotation with a negative distance is equivalent to 1892 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val, 1893 * distance)}. Note also that rotation by any multiple of 64 is a 1894 * no-op, so all but the last six bits of the rotation distance can be 1895 * ignored, even if the distance is negative: {@code rotateLeft(val, 1896 * distance) == rotateLeft(val, distance & 0x3F)}. 1897 * 1898 * @param i the value whose bits are to be rotated left 1899 * @param distance the number of bit positions to rotate left 1900 * @return the value obtained by rotating the two's complement binary 1901 * representation of the specified {@code long} value left by the 1902 * specified number of bits. 1903 * @since 1.5 1904 */ rotateLeft(long i, int distance)1905 public static long rotateLeft(long i, int distance) { 1906 return (i << distance) | (i >>> -distance); 1907 } 1908 1909 /** 1910 * Returns the value obtained by rotating the two's complement binary 1911 * representation of the specified {@code long} value right by the 1912 * specified number of bits. (Bits shifted out of the right hand, or 1913 * low-order, side reenter on the left, or high-order.) 1914 * 1915 * <p>Note that right rotation with a negative distance is equivalent to 1916 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val, 1917 * distance)}. Note also that rotation by any multiple of 64 is a 1918 * no-op, so all but the last six bits of the rotation distance can be 1919 * ignored, even if the distance is negative: {@code rotateRight(val, 1920 * distance) == rotateRight(val, distance & 0x3F)}. 1921 * 1922 * @param i the value whose bits are to be rotated right 1923 * @param distance the number of bit positions to rotate right 1924 * @return the value obtained by rotating the two's complement binary 1925 * representation of the specified {@code long} value right by the 1926 * specified number of bits. 1927 * @since 1.5 1928 */ rotateRight(long i, int distance)1929 public static long rotateRight(long i, int distance) { 1930 return (i >>> distance) | (i << -distance); 1931 } 1932 1933 /** 1934 * Returns the value obtained by reversing the order of the bits in the 1935 * two's complement binary representation of the specified {@code long} 1936 * value. 1937 * 1938 * @param i the value to be reversed 1939 * @return the value obtained by reversing order of the bits in the 1940 * specified {@code long} value. 1941 * @since 1.5 1942 */ reverse(long i)1943 public static long reverse(long i) { 1944 // HD, Figure 7-1 1945 i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L; 1946 i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L; 1947 i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL; 1948 1949 return reverseBytes(i); 1950 } 1951 1952 /** 1953 * Returns the signum function of the specified {@code long} value. (The 1954 * return value is -1 if the specified value is negative; 0 if the 1955 * specified value is zero; and 1 if the specified value is positive.) 1956 * 1957 * @param i the value whose signum is to be computed 1958 * @return the signum function of the specified {@code long} value. 1959 * @since 1.5 1960 */ signum(long i)1961 public static int signum(long i) { 1962 // HD, Section 2-7 1963 return (int) ((i >> 63) | (-i >>> 63)); 1964 } 1965 1966 /** 1967 * Returns the value obtained by reversing the order of the bytes in the 1968 * two's complement representation of the specified {@code long} value. 1969 * 1970 * @param i the value whose bytes are to be reversed 1971 * @return the value obtained by reversing the bytes in the specified 1972 * {@code long} value. 1973 * @since 1.5 1974 */ 1975 @IntrinsicCandidate reverseBytes(long i)1976 public static long reverseBytes(long i) { 1977 i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL; 1978 return (i << 48) | ((i & 0xffff0000L) << 16) | 1979 ((i >>> 16) & 0xffff0000L) | (i >>> 48); 1980 } 1981 1982 /** 1983 * Adds two {@code long} values together as per the + operator. 1984 * 1985 * @param a the first operand 1986 * @param b the second operand 1987 * @return the sum of {@code a} and {@code b} 1988 * @see java.util.function.BinaryOperator 1989 * @since 1.8 1990 */ sum(long a, long b)1991 public static long sum(long a, long b) { 1992 return a + b; 1993 } 1994 1995 /** 1996 * Returns the greater of two {@code long} values 1997 * as if by calling {@link Math#max(long, long) Math.max}. 1998 * 1999 * @param a the first operand 2000 * @param b the second operand 2001 * @return the greater of {@code a} and {@code b} 2002 * @see java.util.function.BinaryOperator 2003 * @since 1.8 2004 */ max(long a, long b)2005 public static long max(long a, long b) { 2006 return Math.max(a, b); 2007 } 2008 2009 /** 2010 * Returns the smaller of two {@code long} values 2011 * as if by calling {@link Math#min(long, long) Math.min}. 2012 * 2013 * @param a the first operand 2014 * @param b the second operand 2015 * @return the smaller of {@code a} and {@code b} 2016 * @see java.util.function.BinaryOperator 2017 * @since 1.8 2018 */ min(long a, long b)2019 public static long min(long a, long b) { 2020 return Math.min(a, b); 2021 } 2022 2023 /** 2024 * Returns an {@link Optional} containing the nominal descriptor for this 2025 * instance, which is the instance itself. 2026 * 2027 * @return an {@link Optional} describing the {@linkplain Long} instance 2028 * @since 12 2029 * @hide 2030 */ 2031 @Override describeConstable()2032 public Optional<Long> describeConstable() { 2033 return Optional.of(this); 2034 } 2035 2036 /** 2037 * Resolves this instance as a {@link ConstantDesc}, the result of which is 2038 * the instance itself. 2039 * 2040 * @param lookup ignored 2041 * @return the {@linkplain Long} instance 2042 * @since 12 2043 * @hide 2044 */ 2045 @Override resolveConstantDesc(MethodHandles.Lookup lookup)2046 public Long resolveConstantDesc(MethodHandles.Lookup lookup) { 2047 return this; 2048 } 2049 2050 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 2051 @java.io.Serial 2052 @Native private static final long serialVersionUID = 4290774380558885855L; 2053 } 2054