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