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