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