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