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