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