1 /* 2 * Copyright (c) 1994, 2023, 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 import java.lang.invoke.MethodHandles; 30 import java.lang.constant.Constable; 31 import java.lang.constant.ConstantDesc; 32 import java.math.*; 33 import java.util.Objects; 34 import java.util.Optional; 35 36 // Android-removed: CDS is not used on Android. 37 // import jdk.internal.misc.CDS; 38 39 import jdk.internal.vm.annotation.ForceInline; 40 import jdk.internal.vm.annotation.IntrinsicCandidate; 41 import jdk.internal.vm.annotation.Stable; 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 buf[--charPos] = Integer.DigitOnes[-i2]; 553 if (i2 < -9) { 554 buf[--charPos] = Integer.DigitTens[-i2]; 555 } 556 557 if (negative) { 558 buf[--charPos] = (byte)'-'; 559 } 560 return charPos; 561 } 562 563 // BEGIN Android-added: char version of getChars(long i, int index, byte[] buf). 564 // for java.lang.AbstractStringBuilder#append(int). getChars(long i, int index, char[] buf)565 static int getChars(long i, int index, char[] buf) { 566 long q; 567 int r; 568 int charPos = index; 569 570 boolean negative = (i < 0); 571 if (!negative) { 572 i = -i; 573 } 574 575 // Get 2 digits/iteration using longs until quotient fits into an int 576 while (i <= Integer.MIN_VALUE) { 577 q = i / 100; 578 r = (int)((q * 100) - i); 579 i = q; 580 buf[--charPos] = (char)Integer.DigitOnes[r]; 581 buf[--charPos] = (char)Integer.DigitTens[r]; 582 } 583 584 // Get 2 digits/iteration using ints 585 int q2; 586 int i2 = (int)i; 587 while (i2 <= -100) { 588 q2 = i2 / 100; 589 r = (q2 * 100) - i2; 590 i2 = q2; 591 buf[--charPos] = (char)Integer.DigitOnes[r]; 592 buf[--charPos] = (char)Integer.DigitTens[r]; 593 } 594 595 // We know there are at most two digits left at this point. 596 q2 = i2 / 10; 597 r = (q2 * 10) - i2; 598 buf[--charPos] = (char)('0' + r); 599 600 // Whatever left is the remaining digit. 601 if (q2 < 0) { 602 buf[--charPos] = (char)('0' - q2); 603 } 604 605 if (negative) { 606 buf[--charPos] = (byte)'-'; 607 } 608 return charPos; 609 } 610 // END Android-added: char version of getChars(long i, int index, byte[] buf). 611 612 /** 613 * Returns the string representation size for a given long value. 614 * 615 * @param x long value 616 * @return string size 617 * 618 * @implNote There are other ways to compute this: e.g. binary search, 619 * but values are biased heavily towards zero, and therefore linear search 620 * wins. The iteration results are also routinely inlined in the generated 621 * code after loop unrolling. 622 */ stringSize(long x)623 static int stringSize(long x) { 624 int d = 1; 625 if (x >= 0) { 626 d = 0; 627 x = -x; 628 } 629 long p = -10; 630 for (int i = 1; i < 19; i++) { 631 if (x > p) 632 return i + d; 633 p = 10 * p; 634 } 635 return 19 + d; 636 } 637 638 /** 639 * Parses the string argument as a signed {@code long} in the 640 * radix specified by the second argument. The characters in the 641 * string must all be digits of the specified radix (as determined 642 * by whether {@link java.lang.Character#digit(char, int)} returns 643 * a nonnegative value), except that the first character may be an 644 * ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to 645 * indicate a negative value or an ASCII plus sign {@code '+'} 646 * ({@code '\u005Cu002B'}) to indicate a positive value. The 647 * resulting {@code long} value is returned. 648 * 649 * <p>Note that neither the character {@code L} 650 * ({@code '\u005Cu004C'}) nor {@code l} 651 * ({@code '\u005Cu006C'}) is permitted to appear at the end 652 * of the string as a type indicator, as would be permitted in 653 * Java programming language source code - except that either 654 * {@code L} or {@code l} may appear as a digit for a 655 * radix greater than or equal to 22. 656 * 657 * <p>An exception of type {@code NumberFormatException} is 658 * thrown if any of the following situations occurs: 659 * <ul> 660 * 661 * <li>The first argument is {@code null} or is a string of 662 * length zero. 663 * 664 * <li>The {@code radix} is either smaller than {@link 665 * java.lang.Character#MIN_RADIX} or larger than {@link 666 * java.lang.Character#MAX_RADIX}. 667 * 668 * <li>Any character of the string is not a digit of the specified 669 * radix, except that the first character may be a minus sign 670 * {@code '-'} ({@code '\u005Cu002d'}) or plus sign {@code 671 * '+'} ({@code '\u005Cu002B'}) provided that the string is 672 * longer than length 1. 673 * 674 * <li>The value represented by the string is not a value of type 675 * {@code long}. 676 * </ul> 677 * 678 * <p>Examples: 679 * <blockquote><pre> 680 * parseLong("0", 10) returns 0L 681 * parseLong("473", 10) returns 473L 682 * parseLong("+42", 10) returns 42L 683 * parseLong("-0", 10) returns 0L 684 * parseLong("-FF", 16) returns -255L 685 * parseLong("1100110", 2) returns 102L 686 * parseLong("99", 8) throws a NumberFormatException 687 * parseLong("Hazelnut", 10) throws a NumberFormatException 688 * parseLong("Hazelnut", 36) returns 1356099454469L 689 * </pre></blockquote> 690 * 691 * @param s the {@code String} containing the 692 * {@code long} representation to be parsed. 693 * @param radix the radix to be used while parsing {@code s}. 694 * @return the {@code long} represented by the string argument in 695 * the specified radix. 696 * @throws NumberFormatException if the string does not contain a 697 * parsable {@code long}. 698 */ parseLong(String s, int radix)699 public static long parseLong(String s, int radix) 700 throws NumberFormatException 701 { 702 if (s == null) { 703 throw new NumberFormatException("Cannot parse null string"); 704 } 705 706 if (radix < Character.MIN_RADIX) { 707 throw new NumberFormatException("radix " + radix + 708 " less than Character.MIN_RADIX"); 709 } 710 if (radix > Character.MAX_RADIX) { 711 throw new NumberFormatException("radix " + radix + 712 " greater than Character.MAX_RADIX"); 713 } 714 715 boolean negative = false; 716 int i = 0, len = s.length(); 717 long limit = -Long.MAX_VALUE; 718 719 if (len > 0) { 720 char firstChar = s.charAt(0); 721 if (firstChar < '0') { // Possible leading "+" or "-" 722 if (firstChar == '-') { 723 negative = true; 724 limit = Long.MIN_VALUE; 725 } else if (firstChar != '+') { 726 throw NumberFormatException.forInputString(s, radix); 727 } 728 729 if (len == 1) { // Cannot have lone "+" or "-" 730 throw NumberFormatException.forInputString(s, radix); 731 } 732 i++; 733 } 734 long multmin = limit / radix; 735 long result = 0; 736 while (i < len) { 737 // Accumulating negatively avoids surprises near MAX_VALUE 738 int digit = Character.digit(s.charAt(i++),radix); 739 if (digit < 0 || result < multmin) { 740 throw NumberFormatException.forInputString(s, radix); 741 } 742 result *= radix; 743 if (result < limit + digit) { 744 throw NumberFormatException.forInputString(s, radix); 745 } 746 result -= digit; 747 } 748 return negative ? result : -result; 749 } else { 750 throw NumberFormatException.forInputString(s, radix); 751 } 752 } 753 754 /** 755 * Parses the {@link CharSequence} argument as a signed {@code long} in 756 * the specified {@code radix}, beginning at the specified 757 * {@code beginIndex} and extending to {@code endIndex - 1}. 758 * 759 * <p>The method does not take steps to guard against the 760 * {@code CharSequence} being mutated while parsing. 761 * 762 * @param s the {@code CharSequence} containing the {@code long} 763 * representation to be parsed 764 * @param beginIndex the beginning index, inclusive. 765 * @param endIndex the ending index, exclusive. 766 * @param radix the radix to be used while parsing {@code s}. 767 * @return the signed {@code long} represented by the subsequence in 768 * the specified radix. 769 * @throws NullPointerException if {@code s} is null. 770 * @throws IndexOutOfBoundsException if {@code beginIndex} is 771 * negative, or if {@code beginIndex} is greater than 772 * {@code endIndex} or if {@code endIndex} is greater than 773 * {@code s.length()}. 774 * @throws NumberFormatException if the {@code CharSequence} does not 775 * contain a parsable {@code long} in the specified 776 * {@code radix}, or if {@code radix} is either smaller than 777 * {@link java.lang.Character#MIN_RADIX} or larger than 778 * {@link java.lang.Character#MAX_RADIX}. 779 * @since 9 780 */ parseLong(CharSequence s, int beginIndex, int endIndex, int radix)781 public static long parseLong(CharSequence s, int beginIndex, int endIndex, int radix) 782 throws NumberFormatException { 783 Objects.requireNonNull(s); 784 Objects.checkFromToIndex(beginIndex, endIndex, s.length()); 785 786 if (radix < Character.MIN_RADIX) { 787 throw new NumberFormatException("radix " + radix + 788 " less than Character.MIN_RADIX"); 789 } 790 if (radix > Character.MAX_RADIX) { 791 throw new NumberFormatException("radix " + radix + 792 " greater than Character.MAX_RADIX"); 793 } 794 795 boolean negative = false; 796 int i = beginIndex; 797 long limit = -Long.MAX_VALUE; 798 799 if (i < endIndex) { 800 char firstChar = s.charAt(i); 801 if (firstChar < '0') { // Possible leading "+" or "-" 802 if (firstChar == '-') { 803 negative = true; 804 limit = Long.MIN_VALUE; 805 } else if (firstChar != '+') { 806 throw NumberFormatException.forCharSequence(s, beginIndex, 807 endIndex, i); 808 } 809 i++; 810 } 811 if (i >= endIndex) { // Cannot have lone "+", "-" or "" 812 throw NumberFormatException.forCharSequence(s, beginIndex, 813 endIndex, i); 814 } 815 long multmin = limit / radix; 816 long result = 0; 817 while (i < endIndex) { 818 // Accumulating negatively avoids surprises near MAX_VALUE 819 int digit = Character.digit(s.charAt(i), radix); 820 if (digit < 0 || result < multmin) { 821 throw NumberFormatException.forCharSequence(s, beginIndex, 822 endIndex, i); 823 } 824 result *= radix; 825 if (result < limit + digit) { 826 throw NumberFormatException.forCharSequence(s, beginIndex, 827 endIndex, i); 828 } 829 i++; 830 result -= digit; 831 } 832 return negative ? result : -result; 833 } else { 834 throw new NumberFormatException(""); 835 } 836 } 837 838 /** 839 * Parses the string argument as a signed decimal {@code long}. 840 * The characters in the string must all be decimal digits, except 841 * that the first character may be an ASCII minus sign {@code '-'} 842 * ({@code \u005Cu002D'}) to indicate a negative value or an 843 * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to 844 * indicate a positive value. The resulting {@code long} value is 845 * returned, exactly as if the argument and the radix {@code 10} 846 * were given as arguments to the {@link 847 * #parseLong(java.lang.String, int)} method. 848 * 849 * <p>Note that neither the character {@code L} 850 * ({@code '\u005Cu004C'}) nor {@code l} 851 * ({@code '\u005Cu006C'}) is permitted to appear at the end 852 * of the string as a type indicator, as would be permitted in 853 * Java programming language source code. 854 * 855 * @param s a {@code String} containing the {@code long} 856 * representation to be parsed 857 * @return the {@code long} represented by the argument in 858 * decimal. 859 * @throws NumberFormatException if the string does not contain a 860 * parsable {@code long}. 861 */ parseLong(String s)862 public static long parseLong(String s) throws NumberFormatException { 863 return parseLong(s, 10); 864 } 865 866 /** 867 * Parses the string argument as an unsigned {@code long} in the 868 * radix specified by the second argument. An unsigned integer 869 * maps the values usually associated with negative numbers to 870 * positive numbers larger than {@code MAX_VALUE}. 871 * 872 * The characters in the string must all be digits of the 873 * specified radix (as determined by whether {@link 874 * java.lang.Character#digit(char, int)} returns a nonnegative 875 * value), except that the first character may be an ASCII plus 876 * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting 877 * integer value is returned. 878 * 879 * <p>An exception of type {@code NumberFormatException} is 880 * thrown if any of the following situations occurs: 881 * <ul> 882 * <li>The first argument is {@code null} or is a string of 883 * length zero. 884 * 885 * <li>The radix is either smaller than 886 * {@link java.lang.Character#MIN_RADIX} or 887 * larger than {@link java.lang.Character#MAX_RADIX}. 888 * 889 * <li>Any character of the string is not a digit of the specified 890 * radix, except that the first character may be a plus sign 891 * {@code '+'} ({@code '\u005Cu002B'}) provided that the 892 * string is longer than length 1. 893 * 894 * <li>The value represented by the string is larger than the 895 * largest unsigned {@code long}, 2<sup>64</sup>-1. 896 * 897 * </ul> 898 * 899 * 900 * @param s the {@code String} containing the unsigned integer 901 * representation to be parsed 902 * @param radix the radix to be used while parsing {@code s}. 903 * @return the unsigned {@code long} represented by the string 904 * argument in the specified radix. 905 * @throws NumberFormatException if the {@code String} 906 * does not contain a parsable {@code long}. 907 * @since 1.8 908 */ parseUnsignedLong(String s, int radix)909 public static long parseUnsignedLong(String s, int radix) 910 throws NumberFormatException { 911 if (s == null) { 912 throw new NumberFormatException("Cannot parse null string"); 913 } 914 915 int len = s.length(); 916 if (len > 0) { 917 char firstChar = s.charAt(0); 918 if (firstChar == '-') { 919 throw new 920 NumberFormatException(String.format("Illegal leading minus sign " + 921 "on unsigned string %s.", s)); 922 } else { 923 if (len <= 12 || // Long.MAX_VALUE in Character.MAX_RADIX is 13 digits 924 (radix == 10 && len <= 18) ) { // Long.MAX_VALUE in base 10 is 19 digits 925 return parseLong(s, radix); 926 } 927 928 // No need for range checks on len due to testing above. 929 long first = parseLong(s, 0, len - 1, radix); 930 int second = Character.digit(s.charAt(len - 1), radix); 931 if (second < 0) { 932 throw new NumberFormatException("Bad digit at end of " + s); 933 } 934 long result = first * radix + second; 935 936 /* 937 * Test leftmost bits of multiprecision extension of first*radix 938 * for overflow. The number of bits needed is defined by 939 * GUARD_BIT = ceil(log2(Character.MAX_RADIX)) + 1 = 7. Then 940 * int guard = radix*(int)(first >>> (64 - GUARD_BIT)) and 941 * overflow is tested by splitting guard in the ranges 942 * guard < 92, 92 <= guard < 128, and 128 <= guard, where 943 * 92 = 128 - Character.MAX_RADIX. Note that guard cannot take 944 * on a value which does not include a prime factor in the legal 945 * radix range. 946 */ 947 int guard = radix * (int) (first >>> 57); 948 if (guard >= 128 || 949 (result >= 0 && guard >= 128 - Character.MAX_RADIX)) { 950 /* 951 * For purposes of exposition, the programmatic statements 952 * below should be taken to be multi-precision, i.e., not 953 * subject to overflow. 954 * 955 * A) Condition guard >= 128: 956 * If guard >= 128 then first*radix >= 2^7 * 2^57 = 2^64 957 * hence always overflow. 958 * 959 * B) Condition guard < 92: 960 * Define left7 = first >>> 57. 961 * Given first = (left7 * 2^57) + (first & (2^57 - 1)) then 962 * result <= (radix*left7)*2^57 + radix*(2^57 - 1) + second. 963 * Thus if radix*left7 < 92, radix <= 36, and second < 36, 964 * then result < 92*2^57 + 36*(2^57 - 1) + 36 = 2^64 hence 965 * never overflow. 966 * 967 * C) Condition 92 <= guard < 128: 968 * first*radix + second >= radix*left7*2^57 + second 969 * so that first*radix + second >= 92*2^57 + 0 > 2^63 970 * 971 * D) Condition guard < 128: 972 * radix*first <= (radix*left7) * 2^57 + radix*(2^57 - 1) 973 * so 974 * radix*first + second <= (radix*left7) * 2^57 + radix*(2^57 - 1) + 36 975 * thus 976 * radix*first + second < 128 * 2^57 + 36*2^57 - radix + 36 977 * whence 978 * radix*first + second < 2^64 + 2^6*2^57 = 2^64 + 2^63 979 * 980 * E) Conditions C, D, and result >= 0: 981 * C and D combined imply the mathematical result 982 * 2^63 < first*radix + second < 2^64 + 2^63. The lower 983 * bound is therefore negative as a signed long, but the 984 * upper bound is too small to overflow again after the 985 * signed long overflows to positive above 2^64 - 1. Hence 986 * result >= 0 implies overflow given C and D. 987 */ 988 throw new NumberFormatException(String.format("String value %s exceeds " + 989 "range of unsigned long.", s)); 990 } 991 return result; 992 } 993 } else { 994 throw NumberFormatException.forInputString(s, radix); 995 } 996 } 997 998 /** 999 * Parses the {@link CharSequence} argument as an unsigned {@code long} in 1000 * the specified {@code radix}, beginning at the specified 1001 * {@code beginIndex} and extending to {@code endIndex - 1}. 1002 * 1003 * <p>The method does not take steps to guard against the 1004 * {@code CharSequence} being mutated while parsing. 1005 * 1006 * @param s the {@code CharSequence} containing the unsigned 1007 * {@code long} representation to be parsed 1008 * @param beginIndex the beginning index, inclusive. 1009 * @param endIndex the ending index, exclusive. 1010 * @param radix the radix to be used while parsing {@code s}. 1011 * @return the unsigned {@code long} represented by the subsequence in 1012 * the specified radix. 1013 * @throws NullPointerException if {@code s} is null. 1014 * @throws IndexOutOfBoundsException if {@code beginIndex} is 1015 * negative, or if {@code beginIndex} is greater than 1016 * {@code endIndex} or if {@code endIndex} is greater than 1017 * {@code s.length()}. 1018 * @throws NumberFormatException if the {@code CharSequence} does not 1019 * contain a parsable unsigned {@code long} in the specified 1020 * {@code radix}, or if {@code radix} is either smaller than 1021 * {@link java.lang.Character#MIN_RADIX} or larger than 1022 * {@link java.lang.Character#MAX_RADIX}. 1023 * @since 9 1024 */ parseUnsignedLong(CharSequence s, int beginIndex, int endIndex, int radix)1025 public static long parseUnsignedLong(CharSequence s, int beginIndex, int endIndex, int radix) 1026 throws NumberFormatException { 1027 Objects.requireNonNull(s); 1028 Objects.checkFromToIndex(beginIndex, endIndex, s.length()); 1029 1030 int start = beginIndex, len = endIndex - beginIndex; 1031 1032 if (len > 0) { 1033 char firstChar = s.charAt(start); 1034 if (firstChar == '-') { 1035 throw new NumberFormatException(String.format("Illegal leading minus sign " + 1036 "on unsigned string %s.", s.subSequence(start, start + len))); 1037 } else { 1038 if (len <= 12 || // Long.MAX_VALUE in Character.MAX_RADIX is 13 digits 1039 (radix == 10 && len <= 18) ) { // Long.MAX_VALUE in base 10 is 19 digits 1040 return parseLong(s, start, start + len, radix); 1041 } 1042 1043 // No need for range checks on end due to testing above. 1044 long first = parseLong(s, start, start + len - 1, radix); 1045 int second = Character.digit(s.charAt(start + len - 1), radix); 1046 if (second < 0) { 1047 throw new NumberFormatException("Bad digit at end of " + 1048 s.subSequence(start, start + len)); 1049 } 1050 long result = first * radix + second; 1051 1052 /* 1053 * Test leftmost bits of multiprecision extension of first*radix 1054 * for overflow. The number of bits needed is defined by 1055 * GUARD_BIT = ceil(log2(Character.MAX_RADIX)) + 1 = 7. Then 1056 * int guard = radix*(int)(first >>> (64 - GUARD_BIT)) and 1057 * overflow is tested by splitting guard in the ranges 1058 * guard < 92, 92 <= guard < 128, and 128 <= guard, where 1059 * 92 = 128 - Character.MAX_RADIX. Note that guard cannot take 1060 * on a value which does not include a prime factor in the legal 1061 * radix range. 1062 */ 1063 int guard = radix * (int) (first >>> 57); 1064 if (guard >= 128 || 1065 (result >= 0 && guard >= 128 - Character.MAX_RADIX)) { 1066 /* 1067 * For purposes of exposition, the programmatic statements 1068 * below should be taken to be multi-precision, i.e., not 1069 * subject to overflow. 1070 * 1071 * A) Condition guard >= 128: 1072 * If guard >= 128 then first*radix >= 2^7 * 2^57 = 2^64 1073 * hence always overflow. 1074 * 1075 * B) Condition guard < 92: 1076 * Define left7 = first >>> 57. 1077 * Given first = (left7 * 2^57) + (first & (2^57 - 1)) then 1078 * result <= (radix*left7)*2^57 + radix*(2^57 - 1) + second. 1079 * Thus if radix*left7 < 92, radix <= 36, and second < 36, 1080 * then result < 92*2^57 + 36*(2^57 - 1) + 36 = 2^64 hence 1081 * never overflow. 1082 * 1083 * C) Condition 92 <= guard < 128: 1084 * first*radix + second >= radix*left7*2^57 + second 1085 * so that first*radix + second >= 92*2^57 + 0 > 2^63 1086 * 1087 * D) Condition guard < 128: 1088 * radix*first <= (radix*left7) * 2^57 + radix*(2^57 - 1) 1089 * so 1090 * radix*first + second <= (radix*left7) * 2^57 + radix*(2^57 - 1) + 36 1091 * thus 1092 * radix*first + second < 128 * 2^57 + 36*2^57 - radix + 36 1093 * whence 1094 * radix*first + second < 2^64 + 2^6*2^57 = 2^64 + 2^63 1095 * 1096 * E) Conditions C, D, and result >= 0: 1097 * C and D combined imply the mathematical result 1098 * 2^63 < first*radix + second < 2^64 + 2^63. The lower 1099 * bound is therefore negative as a signed long, but the 1100 * upper bound is too small to overflow again after the 1101 * signed long overflows to positive above 2^64 - 1. Hence 1102 * result >= 0 implies overflow given C and D. 1103 */ 1104 throw new NumberFormatException(String.format("String value %s exceeds " + 1105 "range of unsigned long.", s.subSequence(start, start + len))); 1106 } 1107 return result; 1108 } 1109 } else { 1110 throw NumberFormatException.forInputString("", radix); 1111 } 1112 } 1113 1114 /** 1115 * Parses the string argument as an unsigned decimal {@code long}. The 1116 * characters in the string must all be decimal digits, except 1117 * that the first character may be an ASCII plus sign {@code 1118 * '+'} ({@code '\u005Cu002B'}). The resulting integer value 1119 * is returned, exactly as if the argument and the radix 10 were 1120 * given as arguments to the {@link 1121 * #parseUnsignedLong(java.lang.String, int)} method. 1122 * 1123 * @param s a {@code String} containing the unsigned {@code long} 1124 * representation to be parsed 1125 * @return the unsigned {@code long} value represented by the decimal string argument 1126 * @throws NumberFormatException if the string does not contain a 1127 * parsable unsigned integer. 1128 * @since 1.8 1129 */ parseUnsignedLong(String s)1130 public static long parseUnsignedLong(String s) throws NumberFormatException { 1131 return parseUnsignedLong(s, 10); 1132 } 1133 1134 /** 1135 * Returns a {@code Long} object holding the value 1136 * extracted from the specified {@code String} when parsed 1137 * with the radix given by the second argument. The first 1138 * argument is interpreted as representing a signed 1139 * {@code long} in the radix specified by the second 1140 * argument, exactly as if the arguments were given to the {@link 1141 * #parseLong(java.lang.String, int)} method. The result is a 1142 * {@code Long} object that represents the {@code long} 1143 * value specified by the string. 1144 * 1145 * <p>In other words, this method returns a {@code Long} object equal 1146 * to the value of: 1147 * 1148 * <blockquote> 1149 * {@code Long.valueOf(Long.parseLong(s, radix))} 1150 * </blockquote> 1151 * 1152 * @param s the string to be parsed 1153 * @param radix the radix to be used in interpreting {@code s} 1154 * @return a {@code Long} object holding the value 1155 * represented by the string argument in the specified 1156 * radix. 1157 * @throws NumberFormatException If the {@code String} does not 1158 * contain a parsable {@code long}. 1159 */ valueOf(String s, int radix)1160 public static Long valueOf(String s, int radix) throws NumberFormatException { 1161 return Long.valueOf(parseLong(s, radix)); 1162 } 1163 1164 /** 1165 * Returns a {@code Long} object holding the value 1166 * of the specified {@code String}. The argument is 1167 * interpreted as representing a signed decimal {@code long}, 1168 * exactly as if the argument were given to the {@link 1169 * #parseLong(java.lang.String)} method. The result is a 1170 * {@code Long} object that represents the integer value 1171 * specified by the string. 1172 * 1173 * <p>In other words, this method returns a {@code Long} object 1174 * equal to the value of: 1175 * 1176 * <blockquote> 1177 * {@code Long.valueOf(Long.parseLong(s))} 1178 * </blockquote> 1179 * 1180 * @param s the string to be parsed. 1181 * @return a {@code Long} object holding the value 1182 * represented by the string argument. 1183 * @throws NumberFormatException If the string cannot be parsed 1184 * as a {@code long}. 1185 */ valueOf(String s)1186 public static Long valueOf(String s) throws NumberFormatException 1187 { 1188 return Long.valueOf(parseLong(s, 10)); 1189 } 1190 1191 private static final class LongCache { LongCache()1192 private LongCache() {} 1193 1194 @Stable 1195 static final Long[] cache; 1196 static Long[] archivedCache; 1197 1198 static { 1199 int size = -(-128) + 127 + 1; 1200 1201 // Load and use the archived cache if it exists 1202 // Android-removed: CDS is not used on Android. 1203 // CDS.initializeFromArchive(LongCache.class); 1204 if (archivedCache == null || archivedCache.length != size) { 1205 Long[] c = new Long[size]; 1206 long value = -128; 1207 for(int i = 0; i < size; i++) { 1208 c[i] = new Long(value++); 1209 } 1210 archivedCache = c; 1211 } 1212 cache = archivedCache; 1213 } 1214 } 1215 1216 /** 1217 * Returns a {@code Long} instance representing the specified 1218 * {@code long} value. 1219 * If a new {@code Long} instance is not required, this method 1220 * should generally be used in preference to the constructor 1221 * {@link #Long(long)}, as this method is likely to yield 1222 * significantly better space and time performance by caching 1223 * frequently requested values. 1224 * 1225 * This method will always cache values in the range -128 to 127, 1226 * inclusive, and may cache other values outside of this range. 1227 * 1228 * @param l a long value. 1229 * @return a {@code Long} instance representing {@code l}. 1230 * @since 1.5 1231 */ 1232 @IntrinsicCandidate valueOf(long l)1233 public static Long valueOf(long l) { 1234 final int offset = 128; 1235 if (l >= -128 && l <= 127) { // will cache 1236 return LongCache.cache[(int)l + offset]; 1237 } 1238 return new Long(l); 1239 } 1240 1241 /** 1242 * Decodes a {@code String} into a {@code Long}. 1243 * Accepts decimal, hexadecimal, and octal numbers given by the 1244 * following grammar: 1245 * 1246 * <blockquote> 1247 * <dl> 1248 * <dt><i>DecodableString:</i> 1249 * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i> 1250 * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i> 1251 * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i> 1252 * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i> 1253 * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i> 1254 * 1255 * <dt><i>Sign:</i> 1256 * <dd>{@code -} 1257 * <dd>{@code +} 1258 * </dl> 1259 * </blockquote> 1260 * 1261 * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i> 1262 * are as defined in section {@jls 3.10.1} of 1263 * <cite>The Java Language Specification</cite>, 1264 * except that underscores are not accepted between digits. 1265 * 1266 * <p>The sequence of characters following an optional 1267 * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", 1268 * "{@code #}", or leading zero) is parsed as by the {@code 1269 * Long.parseLong} method with the indicated radix (10, 16, or 8). 1270 * This sequence of characters must represent a positive value or 1271 * a {@link NumberFormatException} will be thrown. The result is 1272 * negated if first character of the specified {@code String} is 1273 * the minus sign. No whitespace characters are permitted in the 1274 * {@code String}. 1275 * 1276 * @param nm the {@code String} to decode. 1277 * @return a {@code Long} object holding the {@code long} 1278 * value represented by {@code nm} 1279 * @throws NumberFormatException if the {@code String} does not 1280 * contain a parsable {@code long}. 1281 * @see java.lang.Long#parseLong(String, int) 1282 * @since 1.2 1283 */ decode(String nm)1284 public static Long decode(String nm) throws NumberFormatException { 1285 int radix = 10; 1286 int index = 0; 1287 boolean negative = false; 1288 long result; 1289 1290 if (nm.isEmpty()) 1291 throw new NumberFormatException("Zero length string"); 1292 char firstChar = nm.charAt(0); 1293 // Handle sign, if present 1294 if (firstChar == '-') { 1295 negative = true; 1296 index++; 1297 } else if (firstChar == '+') 1298 index++; 1299 1300 // Handle radix specifier, if present 1301 if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) { 1302 index += 2; 1303 radix = 16; 1304 } 1305 else if (nm.startsWith("#", index)) { 1306 index ++; 1307 radix = 16; 1308 } 1309 else if (nm.startsWith("0", index) && nm.length() > 1 + index) { 1310 index ++; 1311 radix = 8; 1312 } 1313 1314 if (nm.startsWith("-", index) || nm.startsWith("+", index)) 1315 throw new NumberFormatException("Sign character in wrong position"); 1316 1317 try { 1318 result = parseLong(nm, index, nm.length(), radix); 1319 result = negative ? -result : result; 1320 } catch (NumberFormatException e) { 1321 // If number is Long.MIN_VALUE, we'll end up here. The next line 1322 // handles this case, and causes any genuine format error to be 1323 // rethrown. 1324 String constant = negative ? ("-" + nm.substring(index)) 1325 : nm.substring(index); 1326 result = parseLong(constant, radix); 1327 } 1328 return result; 1329 } 1330 1331 /** 1332 * The value of the {@code Long}. 1333 * 1334 * @serial 1335 */ 1336 private final long value; 1337 1338 /** 1339 * Constructs a newly allocated {@code Long} object that 1340 * represents the specified {@code long} argument. 1341 * 1342 * @param value the value to be represented by the 1343 * {@code Long} object. 1344 * 1345 * @deprecated 1346 * It is rarely appropriate to use this constructor. The static factory 1347 * {@link #valueOf(long)} is generally a better choice, as it is 1348 * likely to yield significantly better space and time performance. 1349 */ 1350 // Android-changed: not yet forRemoval on Android. 1351 @Deprecated(since="9"/*, forRemoval = true*/) Long(long value)1352 public Long(long value) { 1353 this.value = value; 1354 } 1355 1356 /** 1357 * Constructs a newly allocated {@code Long} object that 1358 * represents the {@code long} value indicated by the 1359 * {@code String} parameter. The string is converted to a 1360 * {@code long} value in exactly the manner used by the 1361 * {@code parseLong} method for radix 10. 1362 * 1363 * @param s the {@code String} to be converted to a 1364 * {@code Long}. 1365 * @throws NumberFormatException if the {@code String} does not 1366 * contain a parsable {@code long}. 1367 * 1368 * @deprecated 1369 * It is rarely appropriate to use this constructor. 1370 * Use {@link #parseLong(String)} to convert a string to a 1371 * {@code long} primitive, or use {@link #valueOf(String)} 1372 * to convert a string to a {@code Long} object. 1373 */ 1374 @Deprecated(since="9"/*, forRemoval = true*/) Long(String s)1375 public Long(String s) throws NumberFormatException { 1376 this.value = parseLong(s, 10); 1377 } 1378 1379 /** 1380 * Returns the value of this {@code Long} as a {@code byte} after 1381 * a narrowing primitive conversion. 1382 * @jls 5.1.3 Narrowing Primitive Conversion 1383 */ byteValue()1384 public byte byteValue() { 1385 return (byte)value; 1386 } 1387 1388 /** 1389 * Returns the value of this {@code Long} as a {@code short} after 1390 * a narrowing primitive conversion. 1391 * @jls 5.1.3 Narrowing Primitive Conversion 1392 */ shortValue()1393 public short shortValue() { 1394 return (short)value; 1395 } 1396 1397 /** 1398 * Returns the value of this {@code Long} as an {@code int} after 1399 * a narrowing primitive conversion. 1400 * @jls 5.1.3 Narrowing Primitive Conversion 1401 */ intValue()1402 public int intValue() { 1403 return (int)value; 1404 } 1405 1406 /** 1407 * Returns the value of this {@code Long} as a 1408 * {@code long} value. 1409 */ 1410 @IntrinsicCandidate longValue()1411 public long longValue() { 1412 return value; 1413 } 1414 1415 /** 1416 * Returns the value of this {@code Long} as a {@code float} after 1417 * a widening primitive conversion. 1418 * @jls 5.1.2 Widening Primitive Conversion 1419 */ floatValue()1420 public float floatValue() { 1421 return (float)value; 1422 } 1423 1424 /** 1425 * Returns the value of this {@code Long} as a {@code double} 1426 * after a widening primitive conversion. 1427 * @jls 5.1.2 Widening Primitive Conversion 1428 */ doubleValue()1429 public double doubleValue() { 1430 return (double)value; 1431 } 1432 1433 /** 1434 * Returns a {@code String} object representing this 1435 * {@code Long}'s value. The value is converted to signed 1436 * decimal representation and returned as a string, exactly as if 1437 * the {@code long} value were given as an argument to the 1438 * {@link java.lang.Long#toString(long)} method. 1439 * 1440 * @return a string representation of the value of this object in 1441 * base 10. 1442 */ toString()1443 public String toString() { 1444 return toString(value); 1445 } 1446 1447 /** 1448 * Returns a hash code for this {@code Long}. The result is 1449 * the exclusive OR of the two halves of the primitive 1450 * {@code long} value held by this {@code Long} 1451 * object. That is, the hashcode is the value of the expression: 1452 * 1453 * <blockquote> 1454 * {@code (int)(this.longValue()^(this.longValue()>>>32))} 1455 * </blockquote> 1456 * 1457 * @return a hash code value for this object. 1458 */ 1459 @Override hashCode()1460 public int hashCode() { 1461 return Long.hashCode(value); 1462 } 1463 1464 /** 1465 * Returns a hash code for a {@code long} value; compatible with 1466 * {@code Long.hashCode()}. 1467 * 1468 * @param value the value to hash 1469 * @return a hash code value for a {@code long} value. 1470 * @since 1.8 1471 */ hashCode(long value)1472 public static int hashCode(long value) { 1473 return (int)(value ^ (value >>> 32)); 1474 } 1475 1476 /** 1477 * Compares this object to the specified object. The result is 1478 * {@code true} if and only if the argument is not 1479 * {@code null} and is a {@code Long} object that 1480 * contains the same {@code long} value as this object. 1481 * 1482 * @param obj the object to compare with. 1483 * @return {@code true} if the objects are the same; 1484 * {@code false} otherwise. 1485 */ equals(Object obj)1486 public boolean equals(Object obj) { 1487 if (obj instanceof Long) { 1488 return value == ((Long)obj).longValue(); 1489 } 1490 return false; 1491 } 1492 1493 /** 1494 * Determines the {@code long} value of the system property 1495 * with the specified name. 1496 * 1497 * <p>The first argument is treated as the name of a system 1498 * property. System properties are accessible through the {@link 1499 * java.lang.System#getProperty(java.lang.String)} method. The 1500 * string value of this property is then interpreted as a {@code 1501 * long} value using the grammar supported by {@link Long#decode decode} 1502 * and a {@code Long} object representing this value is returned. 1503 * 1504 * <p>If there is no property with the specified name, if the 1505 * specified name is empty or {@code null}, or if the property 1506 * does not have the correct numeric format, then {@code null} is 1507 * returned. 1508 * 1509 * <p>In other words, this method returns a {@code Long} object 1510 * equal to the value of: 1511 * 1512 * <blockquote> 1513 * {@code getLong(nm, null)} 1514 * </blockquote> 1515 * 1516 * @param nm property name. 1517 * @return the {@code Long} value of the property. 1518 * @throws SecurityException for the same reasons as 1519 * {@link System#getProperty(String) System.getProperty} 1520 * @see java.lang.System#getProperty(java.lang.String) 1521 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1522 */ getLong(String nm)1523 public static Long getLong(String nm) { 1524 return getLong(nm, null); 1525 } 1526 1527 /** 1528 * Determines the {@code long} value of the system property 1529 * with the specified name. 1530 * 1531 * <p>The first argument is treated as the name of a system 1532 * property. System properties are accessible through the {@link 1533 * java.lang.System#getProperty(java.lang.String)} method. The 1534 * string value of this property is then interpreted as a {@code 1535 * long} value using the grammar supported by {@link Long#decode decode} 1536 * and a {@code Long} object representing this value is returned. 1537 * 1538 * <p>The second argument is the default value. A {@code Long} object 1539 * that represents the value of the second argument is returned if there 1540 * is no property of the specified name, if the property does not have 1541 * the correct numeric format, or if the specified name is empty or null. 1542 * 1543 * <p>In other words, this method returns a {@code Long} object equal 1544 * to the value of: 1545 * 1546 * <blockquote> 1547 * {@code getLong(nm, Long.valueOf(val))} 1548 * </blockquote> 1549 * 1550 * but in practice it may be implemented in a manner such as: 1551 * 1552 * <blockquote><pre> 1553 * Long result = getLong(nm, null); 1554 * return (result == null) ? Long.valueOf(val) : result; 1555 * </pre></blockquote> 1556 * 1557 * to avoid the unnecessary allocation of a {@code Long} object when 1558 * the default value is not needed. 1559 * 1560 * @param nm property name. 1561 * @param val default value. 1562 * @return the {@code Long} value of the property. 1563 * @throws SecurityException for the same reasons as 1564 * {@link System#getProperty(String) System.getProperty} 1565 * @see java.lang.System#getProperty(java.lang.String) 1566 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1567 */ getLong(String nm, long val)1568 public static Long getLong(String nm, long val) { 1569 Long result = Long.getLong(nm, null); 1570 return (result == null) ? Long.valueOf(val) : result; 1571 } 1572 1573 /** 1574 * Returns the {@code long} value of the system property with 1575 * the specified name. The first argument is treated as the name 1576 * of a system property. System properties are accessible through 1577 * the {@link java.lang.System#getProperty(java.lang.String)} 1578 * method. The string value of this property is then interpreted 1579 * as a {@code long} value, as per the 1580 * {@link Long#decode decode} method, and a {@code Long} object 1581 * representing this value is returned; in summary: 1582 * 1583 * <ul> 1584 * <li>If the property value begins with the two ASCII characters 1585 * {@code 0x} or the ASCII character {@code #}, not followed by 1586 * a minus sign, then the rest of it is parsed as a hexadecimal integer 1587 * exactly as for the method {@link #valueOf(java.lang.String, int)} 1588 * with radix 16. 1589 * <li>If the property value begins with the ASCII character 1590 * {@code 0} followed by another character, it is parsed as 1591 * an octal integer exactly as by the method {@link 1592 * #valueOf(java.lang.String, int)} with radix 8. 1593 * <li>Otherwise the property value is parsed as a decimal 1594 * integer exactly as by the method 1595 * {@link #valueOf(java.lang.String, int)} with radix 10. 1596 * </ul> 1597 * 1598 * <p>Note that, in every case, neither {@code L} 1599 * ({@code '\u005Cu004C'}) nor {@code l} 1600 * ({@code '\u005Cu006C'}) is permitted to appear at the end 1601 * of the property value as a type indicator, as would be 1602 * permitted in Java programming language source code. 1603 * 1604 * <p>The second argument is the default value. The default value is 1605 * returned if there is no property of the specified name, if the 1606 * property does not have the correct numeric format, or if the 1607 * specified name is empty or {@code null}. 1608 * 1609 * @param nm property name. 1610 * @param val default value. 1611 * @return the {@code Long} value of the property. 1612 * @throws SecurityException for the same reasons as 1613 * {@link System#getProperty(String) System.getProperty} 1614 * @see System#getProperty(java.lang.String) 1615 * @see System#getProperty(java.lang.String, java.lang.String) 1616 */ getLong(String nm, Long val)1617 public static Long getLong(String nm, Long val) { 1618 String v = null; 1619 try { 1620 v = System.getProperty(nm); 1621 } catch (IllegalArgumentException | NullPointerException e) { 1622 } 1623 if (v != null) { 1624 try { 1625 return Long.decode(v); 1626 } catch (NumberFormatException e) { 1627 } 1628 } 1629 return val; 1630 } 1631 1632 /** 1633 * Compares two {@code Long} objects numerically. 1634 * 1635 * @param anotherLong the {@code Long} to be compared. 1636 * @return the value {@code 0} if this {@code Long} is 1637 * equal to the argument {@code Long}; a value less than 1638 * {@code 0} if this {@code Long} is numerically less 1639 * than the argument {@code Long}; and a value greater 1640 * than {@code 0} if this {@code Long} is numerically 1641 * greater than the argument {@code Long} (signed 1642 * comparison). 1643 * @since 1.2 1644 */ compareTo(Long anotherLong)1645 public int compareTo(Long anotherLong) { 1646 return compare(this.value, anotherLong.value); 1647 } 1648 1649 /** 1650 * Compares two {@code long} values numerically. 1651 * The value returned is identical to what would be returned by: 1652 * <pre> 1653 * Long.valueOf(x).compareTo(Long.valueOf(y)) 1654 * </pre> 1655 * 1656 * @param x the first {@code long} to compare 1657 * @param y the second {@code long} to compare 1658 * @return the value {@code 0} if {@code x == y}; 1659 * a value less than {@code 0} if {@code x < y}; and 1660 * a value greater than {@code 0} if {@code x > y} 1661 * @since 1.7 1662 */ compare(long x, long y)1663 public static int compare(long x, long y) { 1664 return (x < y) ? -1 : ((x == y) ? 0 : 1); 1665 } 1666 1667 /** 1668 * Compares two {@code long} values numerically treating the values 1669 * as unsigned. 1670 * 1671 * @param x the first {@code long} to compare 1672 * @param y the second {@code long} to compare 1673 * @return the value {@code 0} if {@code x == y}; a value less 1674 * than {@code 0} if {@code x < y} as unsigned values; and 1675 * a value greater than {@code 0} if {@code x > y} as 1676 * unsigned values 1677 * @since 1.8 1678 */ 1679 @IntrinsicCandidate compareUnsigned(long x, long y)1680 public static int compareUnsigned(long x, long y) { 1681 return compare(x + MIN_VALUE, y + MIN_VALUE); 1682 } 1683 1684 1685 /** 1686 * Returns the unsigned quotient of dividing the first argument by 1687 * the second where each argument and the result is interpreted as 1688 * an unsigned value. 1689 * 1690 * <p>Note that in two's complement arithmetic, the three other 1691 * basic arithmetic operations of add, subtract, and multiply are 1692 * bit-wise identical if the two operands are regarded as both 1693 * being signed or both being unsigned. Therefore separate {@code 1694 * addUnsigned}, etc. methods are not provided. 1695 * 1696 * @param dividend the value to be divided 1697 * @param divisor the value doing the dividing 1698 * @return the unsigned quotient of the first argument divided by 1699 * the second argument 1700 * @see #remainderUnsigned 1701 * @since 1.8 1702 */ 1703 @IntrinsicCandidate divideUnsigned(long dividend, long divisor)1704 public static long divideUnsigned(long dividend, long divisor) { 1705 /* See Hacker's Delight (2nd ed), section 9.3 */ 1706 if (divisor >= 0) { 1707 final long q = (dividend >>> 1) / divisor << 1; 1708 final long r = dividend - q * divisor; 1709 return q + ((r | ~(r - divisor)) >>> (Long.SIZE - 1)); 1710 } 1711 return (dividend & ~(dividend - divisor)) >>> (Long.SIZE - 1); 1712 } 1713 1714 /** 1715 * Returns the unsigned remainder from dividing the first argument 1716 * by the second where each argument and the result is interpreted 1717 * as an unsigned value. 1718 * 1719 * @param dividend the value to be divided 1720 * @param divisor the value doing the dividing 1721 * @return the unsigned remainder of the first argument divided by 1722 * the second argument 1723 * @see #divideUnsigned 1724 * @since 1.8 1725 */ 1726 @IntrinsicCandidate remainderUnsigned(long dividend, long divisor)1727 public static long remainderUnsigned(long dividend, long divisor) { 1728 /* See Hacker's Delight (2nd ed), section 9.3 */ 1729 if (divisor >= 0) { 1730 final long q = (dividend >>> 1) / divisor << 1; 1731 final long r = dividend - q * divisor; 1732 /* 1733 * Here, 0 <= r < 2 * divisor 1734 * (1) When 0 <= r < divisor, the remainder is simply r. 1735 * (2) Otherwise the remainder is r - divisor. 1736 * 1737 * In case (1), r - divisor < 0. Applying ~ produces a long with 1738 * sign bit 0, so >> produces 0. The returned value is thus r. 1739 * 1740 * In case (2), a similar reasoning shows that >> produces -1, 1741 * so the returned value is r - divisor. 1742 */ 1743 return r - ((~(r - divisor) >> (Long.SIZE - 1)) & divisor); 1744 } 1745 /* 1746 * (1) When dividend >= 0, the remainder is dividend. 1747 * (2) Otherwise 1748 * (2.1) When dividend < divisor, the remainder is dividend. 1749 * (2.2) Otherwise the remainder is dividend - divisor 1750 * 1751 * A reasoning similar to the above shows that the returned value 1752 * is as expected. 1753 */ 1754 return dividend - (((dividend & ~(dividend - divisor)) >> (Long.SIZE - 1)) & divisor); 1755 } 1756 1757 // Bit Twiddling 1758 1759 /** 1760 * The number of bits used to represent a {@code long} value in two's 1761 * complement binary form. 1762 * 1763 * @since 1.5 1764 */ 1765 @Native public static final int SIZE = 64; 1766 1767 /** 1768 * The number of bytes used to represent a {@code long} value in two's 1769 * complement binary form. 1770 * 1771 * @since 1.8 1772 */ 1773 public static final int BYTES = SIZE / Byte.SIZE; 1774 1775 /** 1776 * Returns a {@code long} value with at most a single one-bit, in the 1777 * position of the highest-order ("leftmost") one-bit in the specified 1778 * {@code long} value. Returns zero if the specified value has no 1779 * one-bits in its two's complement binary representation, that is, if it 1780 * is equal to zero. 1781 * 1782 * @param i the value whose highest one bit is to be computed 1783 * @return a {@code long} value with a single one-bit, in the position 1784 * of the highest-order one-bit in the specified value, or zero if 1785 * the specified value is itself equal to zero. 1786 * @since 1.5 1787 */ highestOneBit(long i)1788 public static long highestOneBit(long i) { 1789 return i & (MIN_VALUE >>> numberOfLeadingZeros(i)); 1790 } 1791 1792 /** 1793 * Returns a {@code long} value with at most a single one-bit, in the 1794 * position of the lowest-order ("rightmost") one-bit in the specified 1795 * {@code long} value. Returns zero if the specified value has no 1796 * one-bits in its two's complement binary representation, that is, if it 1797 * is equal to zero. 1798 * 1799 * @param i the value whose lowest one bit is to be computed 1800 * @return a {@code long} value with a single one-bit, in the position 1801 * of the lowest-order one-bit in the specified value, or zero if 1802 * the specified value is itself equal to zero. 1803 * @since 1.5 1804 */ lowestOneBit(long i)1805 public static long lowestOneBit(long i) { 1806 // HD, Section 2-1 1807 return i & -i; 1808 } 1809 1810 /** 1811 * Returns the number of zero bits preceding the highest-order 1812 * ("leftmost") one-bit in the two's complement binary representation 1813 * of the specified {@code long} value. Returns 64 if the 1814 * specified value has no one-bits in its two's complement representation, 1815 * in other words if it is equal to zero. 1816 * 1817 * <p>Note that this method is closely related to the logarithm base 2. 1818 * For all positive {@code long} values x: 1819 * <ul> 1820 * <li>floor(log<sub>2</sub>(x)) = {@code 63 - numberOfLeadingZeros(x)} 1821 * <li>ceil(log<sub>2</sub>(x)) = {@code 64 - numberOfLeadingZeros(x - 1)} 1822 * </ul> 1823 * 1824 * @param i the value whose number of leading zeros is to be computed 1825 * @return the number of zero bits preceding the highest-order 1826 * ("leftmost") one-bit in the two's complement binary representation 1827 * of the specified {@code long} value, or 64 if the value 1828 * is equal to zero. 1829 * @since 1.5 1830 */ 1831 @IntrinsicCandidate numberOfLeadingZeros(long i)1832 public static int numberOfLeadingZeros(long i) { 1833 int x = (int)(i >>> 32); 1834 return x == 0 ? 32 + Integer.numberOfLeadingZeros((int)i) 1835 : Integer.numberOfLeadingZeros(x); 1836 } 1837 1838 /** 1839 * Returns the number of zero bits following the lowest-order ("rightmost") 1840 * one-bit in the two's complement binary representation of the specified 1841 * {@code long} value. Returns 64 if the specified value has no 1842 * one-bits in its two's complement representation, in other words if it is 1843 * equal to zero. 1844 * 1845 * @param i the value whose number of trailing zeros is to be computed 1846 * @return the number of zero bits following the lowest-order ("rightmost") 1847 * one-bit in the two's complement binary representation of the 1848 * specified {@code long} value, or 64 if the value is equal 1849 * to zero. 1850 * @since 1.5 1851 */ 1852 @IntrinsicCandidate numberOfTrailingZeros(long i)1853 public static int numberOfTrailingZeros(long i) { 1854 int x = (int)i; 1855 return x == 0 ? 32 + Integer.numberOfTrailingZeros((int)(i >>> 32)) 1856 : Integer.numberOfTrailingZeros(x); 1857 } 1858 1859 /** 1860 * Returns the number of one-bits in the two's complement binary 1861 * representation of the specified {@code long} value. This function is 1862 * sometimes referred to as the <i>population count</i>. 1863 * 1864 * @param i the value whose bits are to be counted 1865 * @return the number of one-bits in the two's complement binary 1866 * representation of the specified {@code long} value. 1867 * @since 1.5 1868 */ 1869 @IntrinsicCandidate bitCount(long i)1870 public static int bitCount(long i) { 1871 // HD, Figure 5-2 1872 i = i - ((i >>> 1) & 0x5555555555555555L); 1873 i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L); 1874 i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL; 1875 i = i + (i >>> 8); 1876 i = i + (i >>> 16); 1877 i = i + (i >>> 32); 1878 return (int)i & 0x7f; 1879 } 1880 1881 /** 1882 * Returns the value obtained by rotating the two's complement binary 1883 * representation of the specified {@code long} value left by the 1884 * specified number of bits. (Bits shifted out of the left hand, or 1885 * high-order, side reenter on the right, or low-order.) 1886 * 1887 * <p>Note that left rotation with a negative distance is equivalent to 1888 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val, 1889 * distance)}. Note also that rotation by any multiple of 64 is a 1890 * no-op, so all but the last six bits of the rotation distance can be 1891 * ignored, even if the distance is negative: {@code rotateLeft(val, 1892 * distance) == rotateLeft(val, distance & 0x3F)}. 1893 * 1894 * @param i the value whose bits are to be rotated left 1895 * @param distance the number of bit positions to rotate left 1896 * @return the value obtained by rotating the two's complement binary 1897 * representation of the specified {@code long} value left by the 1898 * specified number of bits. 1899 * @since 1.5 1900 */ rotateLeft(long i, int distance)1901 public static long rotateLeft(long i, int distance) { 1902 return (i << distance) | (i >>> -distance); 1903 } 1904 1905 /** 1906 * Returns the value obtained by rotating the two's complement binary 1907 * representation of the specified {@code long} value right by the 1908 * specified number of bits. (Bits shifted out of the right hand, or 1909 * low-order, side reenter on the left, or high-order.) 1910 * 1911 * <p>Note that right rotation with a negative distance is equivalent to 1912 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val, 1913 * distance)}. Note also that rotation by any multiple of 64 is a 1914 * no-op, so all but the last six bits of the rotation distance can be 1915 * ignored, even if the distance is negative: {@code rotateRight(val, 1916 * distance) == rotateRight(val, distance & 0x3F)}. 1917 * 1918 * @param i the value whose bits are to be rotated right 1919 * @param distance the number of bit positions to rotate right 1920 * @return the value obtained by rotating the two's complement binary 1921 * representation of the specified {@code long} value right by the 1922 * specified number of bits. 1923 * @since 1.5 1924 */ rotateRight(long i, int distance)1925 public static long rotateRight(long i, int distance) { 1926 return (i >>> distance) | (i << -distance); 1927 } 1928 1929 /** 1930 * Returns the value obtained by reversing the order of the bits in the 1931 * two's complement binary representation of the specified {@code long} 1932 * value. 1933 * 1934 * @param i the value to be reversed 1935 * @return the value obtained by reversing order of the bits in the 1936 * specified {@code long} value. 1937 * @since 1.5 1938 */ 1939 @IntrinsicCandidate reverse(long i)1940 public static long reverse(long i) { 1941 // HD, Figure 7-1 1942 i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L; 1943 i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L; 1944 i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL; 1945 1946 return reverseBytes(i); 1947 } 1948 1949 // Android-changed: marked as hide while a compiler plugin issue is not resolved. 1950 /** 1951 * Returns the value obtained by compressing the bits of the 1952 * specified {@code long} value, {@code i}, in accordance with 1953 * the specified bit mask. 1954 * <p> 1955 * For each one-bit value {@code mb} of the mask, from least 1956 * significant to most significant, the bit value of {@code i} at 1957 * the same bit location as {@code mb} is assigned to the compressed 1958 * value contiguously starting from the least significant bit location. 1959 * All the upper remaining bits of the compressed value are set 1960 * to zero. 1961 * 1962 * @apiNote 1963 * Consider the simple case of compressing the digits of a hexadecimal 1964 * value: 1965 * {@snippet lang="java" : 1966 * // Compressing drink to food 1967 * compress(0xCAFEBABEL, 0xFF00FFF0L) == 0xCABABL 1968 * } 1969 * Starting from the least significant hexadecimal digit at position 0 1970 * from the right, the mask {@code 0xFF00FFF0} selects hexadecimal digits 1971 * at positions 1, 2, 3, 6 and 7 of {@code 0xCAFEBABE}. The selected digits 1972 * occur in the resulting compressed value contiguously from digit position 1973 * 0 in the same order. 1974 * <p> 1975 * The following identities all return {@code true} and are helpful to 1976 * understand the behaviour of {@code compress}: 1977 * {@snippet lang="java" : 1978 * // Returns 1 if the bit at position n is one 1979 * compress(x, 1L << n) == (x >> n & 1) 1980 * 1981 * // Logical shift right 1982 * compress(x, -1L << n) == x >>> n 1983 * 1984 * // Any bits not covered by the mask are ignored 1985 * compress(x, m) == compress(x & m, m) 1986 * 1987 * // Compressing a value by itself 1988 * compress(m, m) == (m == -1 || m == 0) ? m : (1L << bitCount(m)) - 1 1989 * 1990 * // Expanding then compressing with the same mask 1991 * compress(expand(x, m), m) == x & compress(m, m) 1992 * } 1993 * <p> 1994 * The Sheep And Goats (SAG) operation (see Hacker's Delight, section 7.7) 1995 * can be implemented as follows: 1996 * {@snippet lang="java" : 1997 * long compressLeft(long i, long mask) { 1998 * // This implementation follows the description in Hacker's Delight which 1999 * // is informative. A more optimal implementation is: 2000 * // Long.compress(i, mask) << -Long.bitCount(mask) 2001 * return Long.reverse( 2002 * Long.compress(Long.reverse(i), Long.reverse(mask))); 2003 * } 2004 * 2005 * long sag(long i, long mask) { 2006 * return compressLeft(i, mask) | Long.compress(i, ~mask); 2007 * } 2008 * 2009 * // Separate the sheep from the goats 2010 * sag(0x00000000_CAFEBABEL, 0xFFFFFFFF_FF00FFF0L) == 0x00000000_CABABFEEL 2011 * } 2012 * 2013 * @param i the value whose bits are to be compressed 2014 * @param mask the bit mask 2015 * @return the compressed value 2016 * @see #expand 2017 * @since 19 2018 */ 2019 @IntrinsicCandidate compress(long i, long mask)2020 public static long compress(long i, long mask) { 2021 // See Hacker's Delight (2nd ed) section 7.4 Compress, or Generalized Extract 2022 2023 i = i & mask; // Clear irrelevant bits 2024 long maskCount = ~mask << 1; // Count 0's to right 2025 2026 for (int j = 0; j < 6; j++) { 2027 // Parallel prefix 2028 // Mask prefix identifies bits of the mask that have an odd number of 0's to the right 2029 long maskPrefix = parallelSuffix(maskCount); 2030 // Bits to move 2031 long maskMove = maskPrefix & mask; 2032 // Compress mask 2033 mask = (mask ^ maskMove) | (maskMove >>> (1 << j)); 2034 // Bits of i to be moved 2035 long t = i & maskMove; 2036 // Compress i 2037 i = (i ^ t) | (t >>> (1 << j)); 2038 // Adjust the mask count by identifying bits that have 0 to the right 2039 maskCount = maskCount & ~maskPrefix; 2040 } 2041 return i; 2042 } 2043 2044 // Android-changed: marked as hide while a compiler plugin issue is not resolved. 2045 /** 2046 * Returns the value obtained by expanding the bits of the 2047 * specified {@code long} value, {@code i}, in accordance with 2048 * the specified bit mask. 2049 * <p> 2050 * For each one-bit value {@code mb} of the mask, from least 2051 * significant to most significant, the next contiguous bit value 2052 * of {@code i} starting at the least significant bit is assigned 2053 * to the expanded value at the same bit location as {@code mb}. 2054 * All other remaining bits of the expanded value are set to zero. 2055 * 2056 * @apiNote 2057 * Consider the simple case of expanding the digits of a hexadecimal 2058 * value: 2059 * {@snippet lang="java" : 2060 * expand(0x0000CABABL, 0xFF00FFF0L) == 0xCA00BAB0L 2061 * } 2062 * Starting from the least significant hexadecimal digit at position 0 2063 * from the right, the mask {@code 0xFF00FFF0} selects the first five 2064 * hexadecimal digits of {@code 0x0000CABAB}. The selected digits occur 2065 * in the resulting expanded value in order at positions 1, 2, 3, 6, and 7. 2066 * <p> 2067 * The following identities all return {@code true} and are helpful to 2068 * understand the behaviour of {@code expand}: 2069 * {@snippet lang="java" : 2070 * // Logically shift right the bit at position 0 2071 * expand(x, 1L << n) == (x & 1) << n 2072 * 2073 * // Logically shift right 2074 * expand(x, -1L << n) == x << n 2075 * 2076 * // Expanding all bits returns the mask 2077 * expand(-1L, m) == m 2078 * 2079 * // Any bits not covered by the mask are ignored 2080 * expand(x, m) == expand(x, m) & m 2081 * 2082 * // Compressing then expanding with the same mask 2083 * expand(compress(x, m), m) == x & m 2084 * } 2085 * <p> 2086 * The select operation for determining the position of the one-bit with 2087 * index {@code n} in a {@code long} value can be implemented as follows: 2088 * {@snippet lang="java" : 2089 * long select(long i, long n) { 2090 * // the one-bit in i (the mask) with index n 2091 * long nthBit = Long.expand(1L << n, i); 2092 * // the bit position of the one-bit with index n 2093 * return Long.numberOfTrailingZeros(nthBit); 2094 * } 2095 * 2096 * // The one-bit with index 0 is at bit position 1 2097 * select(0b10101010_10101010, 0) == 1 2098 * // The one-bit with index 3 is at bit position 7 2099 * select(0b10101010_10101010, 3) == 7 2100 * } 2101 * 2102 * @param i the value whose bits are to be expanded 2103 * @param mask the bit mask 2104 * @return the expanded value 2105 * @see #compress 2106 */ 2107 @IntrinsicCandidate expand(long i, long mask)2108 public static long expand(long i, long mask) { 2109 // Save original mask 2110 long originalMask = mask; 2111 // Count 0's to right 2112 long maskCount = ~mask << 1; 2113 long maskPrefix = parallelSuffix(maskCount); 2114 // Bits to move 2115 long maskMove1 = maskPrefix & mask; 2116 // Compress mask 2117 mask = (mask ^ maskMove1) | (maskMove1 >>> (1 << 0)); 2118 maskCount = maskCount & ~maskPrefix; 2119 2120 maskPrefix = parallelSuffix(maskCount); 2121 // Bits to move 2122 long maskMove2 = maskPrefix & mask; 2123 // Compress mask 2124 mask = (mask ^ maskMove2) | (maskMove2 >>> (1 << 1)); 2125 maskCount = maskCount & ~maskPrefix; 2126 2127 maskPrefix = parallelSuffix(maskCount); 2128 // Bits to move 2129 long maskMove3 = maskPrefix & mask; 2130 // Compress mask 2131 mask = (mask ^ maskMove3) | (maskMove3 >>> (1 << 2)); 2132 maskCount = maskCount & ~maskPrefix; 2133 2134 maskPrefix = parallelSuffix(maskCount); 2135 // Bits to move 2136 long maskMove4 = maskPrefix & mask; 2137 // Compress mask 2138 mask = (mask ^ maskMove4) | (maskMove4 >>> (1 << 3)); 2139 maskCount = maskCount & ~maskPrefix; 2140 2141 maskPrefix = parallelSuffix(maskCount); 2142 // Bits to move 2143 long maskMove5 = maskPrefix & mask; 2144 // Compress mask 2145 mask = (mask ^ maskMove5) | (maskMove5 >>> (1 << 4)); 2146 maskCount = maskCount & ~maskPrefix; 2147 2148 maskPrefix = parallelSuffix(maskCount); 2149 // Bits to move 2150 long maskMove6 = maskPrefix & mask; 2151 2152 long t = i << (1 << 5); 2153 i = (i & ~maskMove6) | (t & maskMove6); 2154 t = i << (1 << 4); 2155 i = (i & ~maskMove5) | (t & maskMove5); 2156 t = i << (1 << 3); 2157 i = (i & ~maskMove4) | (t & maskMove4); 2158 t = i << (1 << 2); 2159 i = (i & ~maskMove3) | (t & maskMove3); 2160 t = i << (1 << 1); 2161 i = (i & ~maskMove2) | (t & maskMove2); 2162 t = i << (1 << 0); 2163 i = (i & ~maskMove1) | (t & maskMove1); 2164 2165 // Clear irrelevant bits 2166 return i & originalMask; 2167 } 2168 2169 @ForceInline parallelSuffix(long maskCount)2170 private static long parallelSuffix(long maskCount) { 2171 long maskPrefix = maskCount ^ (maskCount << 1); 2172 maskPrefix = maskPrefix ^ (maskPrefix << 2); 2173 maskPrefix = maskPrefix ^ (maskPrefix << 4); 2174 maskPrefix = maskPrefix ^ (maskPrefix << 8); 2175 maskPrefix = maskPrefix ^ (maskPrefix << 16); 2176 maskPrefix = maskPrefix ^ (maskPrefix << 32); 2177 return maskPrefix; 2178 } 2179 2180 /** 2181 * Returns the signum function of the specified {@code long} value. (The 2182 * return value is -1 if the specified value is negative; 0 if the 2183 * specified value is zero; and 1 if the specified value is positive.) 2184 * 2185 * @param i the value whose signum is to be computed 2186 * @return the signum function of the specified {@code long} value. 2187 * @since 1.5 2188 */ signum(long i)2189 public static int signum(long i) { 2190 // HD, Section 2-7 2191 return (int) ((i >> 63) | (-i >>> 63)); 2192 } 2193 2194 /** 2195 * Returns the value obtained by reversing the order of the bytes in the 2196 * two's complement representation of the specified {@code long} value. 2197 * 2198 * @param i the value whose bytes are to be reversed 2199 * @return the value obtained by reversing the bytes in the specified 2200 * {@code long} value. 2201 * @since 1.5 2202 */ 2203 @IntrinsicCandidate reverseBytes(long i)2204 public static long reverseBytes(long i) { 2205 i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL; 2206 return (i << 48) | ((i & 0xffff0000L) << 16) | 2207 ((i >>> 16) & 0xffff0000L) | (i >>> 48); 2208 } 2209 2210 /** 2211 * Adds two {@code long} values together as per the + operator. 2212 * 2213 * @param a the first operand 2214 * @param b the second operand 2215 * @return the sum of {@code a} and {@code b} 2216 * @see java.util.function.BinaryOperator 2217 * @since 1.8 2218 */ sum(long a, long b)2219 public static long sum(long a, long b) { 2220 return a + b; 2221 } 2222 2223 /** 2224 * Returns the greater of two {@code long} values 2225 * as if by calling {@link Math#max(long, long) Math.max}. 2226 * 2227 * @param a the first operand 2228 * @param b the second operand 2229 * @return the greater of {@code a} and {@code b} 2230 * @see java.util.function.BinaryOperator 2231 * @since 1.8 2232 */ max(long a, long b)2233 public static long max(long a, long b) { 2234 return Math.max(a, b); 2235 } 2236 2237 /** 2238 * Returns the smaller of two {@code long} values 2239 * as if by calling {@link Math#min(long, long) Math.min}. 2240 * 2241 * @param a the first operand 2242 * @param b the second operand 2243 * @return the smaller of {@code a} and {@code b} 2244 * @see java.util.function.BinaryOperator 2245 * @since 1.8 2246 */ min(long a, long b)2247 public static long min(long a, long b) { 2248 return Math.min(a, b); 2249 } 2250 2251 /** 2252 * Returns an {@link Optional} containing the nominal descriptor for this 2253 * instance, which is the instance itself. 2254 * 2255 * @return an {@link Optional} describing the {@linkplain Long} instance 2256 * @since 12 2257 * @hide 2258 */ 2259 @Override describeConstable()2260 public Optional<Long> describeConstable() { 2261 return Optional.of(this); 2262 } 2263 2264 /** 2265 * Resolves this instance as a {@link ConstantDesc}, the result of which is 2266 * the instance itself. 2267 * 2268 * @param lookup ignored 2269 * @return the {@linkplain Long} instance 2270 * @since 12 2271 * @hide 2272 */ 2273 @Override resolveConstantDesc(MethodHandles.Lookup lookup)2274 public Long resolveConstantDesc(MethodHandles.Lookup lookup) { 2275 return this; 2276 } 2277 2278 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 2279 @java.io.Serial 2280 @Native private static final long serialVersionUID = 4290774380558885855L; 2281 } 2282