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