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