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