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 JDK1.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 JDK1.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 JDK 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 JDK 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 JDK 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 {@code beginIndex} 610 * and extending to the end of the sequence. 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 radix the radix to be used while parsing {@code s}. 618 * @param beginIndex the beginning index, inclusive. 619 * @return the signed {@code long} represented by the subsequence in 620 * the specified radix. 621 * @throws NullPointerException if {@code s} is null. 622 * @throws IndexOutOfBoundsException if {@code beginIndex} is 623 * negative, or if {@code beginIndex} is greater than 624 * {@code s.length()}. 625 * @throws NumberFormatException if the {@code CharSequence} does not 626 * contain a parsable {@code long} in the specified 627 * {@code radix}, or if {@code radix} is either smaller than 628 * {@link java.lang.Character#MIN_RADIX} or larger than 629 * {@link java.lang.Character#MAX_RADIX}. 630 * @since 1.9 631 */ 632 static long parseLong(CharSequence s, int radix, int beginIndex) 633 throws NumberFormatException { 634 // forces a null check of s 635 return parseLong(s, radix, beginIndex, s.length()); 636 } 637 638 /** 639 * Parses the {@link CharSequence} argument as a signed {@code long} in 640 * the specified {@code radix}, beginning at the specified 641 * {@code beginIndex} and extending to {@code endIndex - 1}. 642 * 643 * <p>The method does not take steps to guard against the 644 * {@code CharSequence} being mutated while parsing. 645 * 646 * @param s the {@code CharSequence} containing the {@code long} 647 * representation to be parsed 648 * @param radix the radix to be used while parsing {@code s}. 649 * @param beginIndex the beginning index, inclusive. 650 * @param endIndex the ending index, exclusive. 651 * @return the signed {@code long} represented by the subsequence in 652 * the specified radix. 653 * @throws NullPointerException if {@code s} is null. 654 * @throws IndexOutOfBoundsException if {@code beginIndex} is 655 * negative, or if {@code beginIndex} is greater than 656 * {@code endIndex} or if {@code endIndex} is greater than 657 * {@code s.length()}. 658 * @throws NumberFormatException if the {@code CharSequence} does not 659 * contain a parsable {@code int} in the specified 660 * {@code radix}, or if {@code radix} is either smaller than 661 * {@link java.lang.Character#MIN_RADIX} or larger than 662 * {@link java.lang.Character#MAX_RADIX}. 663 * @since 1.9 664 */ 665 static long parseLong(CharSequence s, int radix, int beginIndex, int endIndex) 666 throws NumberFormatException { 667 s = Objects.requireNonNull(s); 668 669 if (beginIndex < 0 || beginIndex > endIndex || endIndex > s.length()) { 670 throw new IndexOutOfBoundsException(); 671 } 672 if (radix < Character.MIN_RADIX) { 673 throw new NumberFormatException("radix " + radix + 674 " less than Character.MIN_RADIX"); 675 } 676 if (radix > Character.MAX_RADIX) { 677 throw new NumberFormatException("radix " + radix + 678 " greater than Character.MAX_RADIX"); 679 } 680 681 boolean negative = false; 682 int i = beginIndex; 683 long limit = -Long.MAX_VALUE; 684 685 if (i < endIndex) { 686 char firstChar = s.charAt(i); 687 if (firstChar < '0') { // Possible leading "+" or "-" 688 if (firstChar == '-') { 689 negative = true; 690 limit = Long.MIN_VALUE; 691 } else if (firstChar != '+') { 692 throw NumberFormatException.forCharSequence(s, beginIndex, 693 endIndex, i); 694 } 695 i++; 696 } 697 if (i >= endIndex) { // Cannot have lone "+", "-" or "" 698 throw NumberFormatException.forCharSequence(s, beginIndex, 699 endIndex, i); 700 } 701 long multmin = limit / radix; 702 long result = 0; 703 while (i < endIndex) { 704 // Accumulating negatively avoids surprises near MAX_VALUE 705 int digit = Character.digit(s.charAt(i++), radix); 706 if (digit < 0 || result < multmin) { 707 throw NumberFormatException.forCharSequence(s, beginIndex, 708 endIndex, i); 709 } 710 result *= radix; 711 if (result < limit + digit) { 712 throw NumberFormatException.forCharSequence(s, beginIndex, 713 endIndex, i); 714 } 715 result -= digit; 716 } 717 return negative ? result : -result; 718 } else { 719 throw new NumberFormatException(""); 720 } 721 } 722 723 /** 724 * Parses the string argument as a signed decimal {@code long}. 725 * The characters in the string must all be decimal digits, except 726 * that the first character may be an ASCII minus sign {@code '-'} 727 * ({@code \u005Cu002D'}) to indicate a negative value or an 728 * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to 729 * indicate a positive value. The resulting {@code long} value is 730 * returned, exactly as if the argument and the radix {@code 10} 731 * were given as arguments to the {@link 732 * #parseLong(java.lang.String, int)} method. 733 * 734 * <p>Note that neither the character {@code L} 735 * ({@code '\u005Cu004C'}) nor {@code l} 736 * ({@code '\u005Cu006C'}) is permitted to appear at the end 737 * of the string as a type indicator, as would be permitted in 738 * Java programming language source code. 739 * 740 * @param s a {@code String} containing the {@code long} 741 * representation to be parsed 742 * @return the {@code long} represented by the argument in 743 * decimal. 744 * @throws NumberFormatException if the string does not contain a 745 * parsable {@code long}. 746 */ 747 public static long parseLong(String s) throws NumberFormatException { 748 return parseLong(s, 10); 749 } 750 751 /** 752 * Parses the string argument as an unsigned {@code long} in the 753 * radix specified by the second argument. An unsigned integer 754 * maps the values usually associated with negative numbers to 755 * positive numbers larger than {@code MAX_VALUE}. 756 * 757 * The characters in the string must all be digits of the 758 * specified radix (as determined by whether {@link 759 * java.lang.Character#digit(char, int)} returns a nonnegative 760 * value), except that the first character may be an ASCII plus 761 * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting 762 * integer value is returned. 763 * 764 * <p>An exception of type {@code NumberFormatException} is 765 * thrown if any of the following situations occurs: 766 * <ul> 767 * <li>The first argument is {@code null} or is a string of 768 * length zero. 769 * 770 * <li>The radix is either smaller than 771 * {@link java.lang.Character#MIN_RADIX} or 772 * larger than {@link java.lang.Character#MAX_RADIX}. 773 * 774 * <li>Any character of the string is not a digit of the specified 775 * radix, except that the first character may be a plus sign 776 * {@code '+'} ({@code '\u005Cu002B'}) provided that the 777 * string is longer than length 1. 778 * 779 * <li>The value represented by the string is larger than the 780 * largest unsigned {@code long}, 2<sup>64</sup>-1. 781 * 782 * </ul> 783 * 784 * 785 * @param s the {@code String} containing the unsigned integer 786 * representation to be parsed 787 * @param radix the radix to be used while parsing {@code s}. 788 * @return the unsigned {@code long} represented by the string 789 * argument in the specified radix. 790 * @throws NumberFormatException if the {@code String} 791 * does not contain a parsable {@code long}. 792 * @since 1.8 793 */ 794 public static long parseUnsignedLong(String s, int radix) 795 throws NumberFormatException { 796 if (s == null) { 797 throw new NumberFormatException("null"); 798 } 799 800 int len = s.length(); 801 if (len > 0) { 802 char firstChar = s.charAt(0); 803 if (firstChar == '-') { 804 throw new 805 NumberFormatException(String.format("Illegal leading minus sign " + 806 "on unsigned string %s.", s)); 807 } else { 808 if (len <= 12 || // Long.MAX_VALUE in Character.MAX_RADIX is 13 digits 809 (radix == 10 && len <= 18) ) { // Long.MAX_VALUE in base 10 is 19 digits 810 return parseLong(s, radix); 811 } 812 813 // No need for range checks on len due to testing above. 814 long first = parseLong(s, radix, 0, len - 1); 815 int second = Character.digit(s.charAt(len - 1), radix); 816 if (second < 0) { 817 throw new NumberFormatException("Bad digit at end of " + s); 818 } 819 long result = first * radix + second; 820 if (compareUnsigned(result, first) < 0) { 821 /* 822 * The maximum unsigned value, (2^64)-1, takes at 823 * most one more digit to represent than the 824 * maximum signed value, (2^63)-1. Therefore, 825 * parsing (len - 1) digits will be appropriately 826 * in-range of the signed parsing. In other 827 * words, if parsing (len -1) digits overflows 828 * signed parsing, parsing len digits will 829 * certainly overflow unsigned parsing. 830 * 831 * The compareUnsigned check above catches 832 * situations where an unsigned overflow occurs 833 * incorporating the contribution of the final 834 * digit. 835 */ 836 throw new NumberFormatException(String.format("String value %s exceeds " + 837 "range of unsigned long.", s)); 838 } 839 return result; 840 } 841 } else { 842 throw NumberFormatException.forInputString(s); 843 } 844 } 845 846 /** 847 * Parses the {@link CharSequence} argument as an unsigned {@code long} in 848 * the specified {@code radix}, beginning at the specified 849 * {@code beginIndex} and extending to the end of the sequence. 850 * 851 * <p>The method does not take steps to guard against the 852 * {@code CharSequence} being mutated while parsing. 853 * 854 * @param s the {@code CharSequence} containing the unsigned 855 * {@code long} representation to be parsed 856 * @param radix the radix to be used while parsing {@code s}. 857 * @param beginIndex the beginning index, inclusive. 858 * @return the unsigned {@code long} represented by the subsequence in 859 * the specified radix. 860 * @throws NullPointerException if {@code s} is null. 861 * @throws IndexOutOfBoundsException if {@code beginIndex} is 862 * negative, or if {@code beginIndex} is greater than 863 * {@code s.length()}. 864 * @throws NumberFormatException if the {@code CharSequence} does not 865 * contain a parsable unsigned {@code long} in the specified 866 * {@code radix}, or if {@code radix} is either smaller than 867 * {@link java.lang.Character#MIN_RADIX} or larger than 868 * {@link java.lang.Character#MAX_RADIX}. 869 * @since 1.9 870 */ 871 static long parseUnsignedLong(CharSequence s, int radix, int beginIndex) 872 throws NumberFormatException { 873 // forces a null check of s 874 return parseUnsignedLong(s, radix, beginIndex, s.length()); 875 } 876 877 /** 878 * Parses the {@link CharSequence} argument as an unsigned {@code long} in 879 * the specified {@code radix}, beginning at the specified 880 * {@code beginIndex} and extending to {@code endIndex - 1}. 881 * 882 * <p>The method does not take steps to guard against the 883 * {@code CharSequence} being mutated while parsing. 884 * 885 * @param s the {@code CharSequence} containing the unsigned 886 * {@code long} representation to be parsed 887 * @param radix the radix to be used while parsing {@code s}. 888 * @param beginIndex the beginning index, inclusive. 889 * @param endIndex the ending index, exclusive. 890 * @return the unsigned {@code long} represented by the subsequence in 891 * the specified radix. 892 * @throws NullPointerException if {@code s} is null. 893 * @throws IndexOutOfBoundsException if {@code beginIndex} is 894 * negative, or if {@code beginIndex} is greater than 895 * {@code endIndex} or if {@code endIndex} is greater than 896 * {@code s.length()}. 897 * @throws NumberFormatException if the {@code CharSequence} does not 898 * contain a parsable unsigned {@code long} in the specified 899 * {@code radix}, or if {@code radix} is either smaller than 900 * {@link java.lang.Character#MIN_RADIX} or larger than 901 * {@link java.lang.Character#MAX_RADIX}. 902 * @since 1.9 903 */ 904 static long parseUnsignedLong(CharSequence s, int radix, int beginIndex, int endIndex) 905 throws NumberFormatException { 906 s = Objects.requireNonNull(s); 907 908 if (beginIndex < 0 || beginIndex > endIndex || endIndex > s.length()) { 909 throw new IndexOutOfBoundsException(); 910 } 911 int start = beginIndex, len = endIndex - beginIndex; 912 913 if (len > 0) { 914 char firstChar = s.charAt(start); 915 if (firstChar == '-') { 916 throw new NumberFormatException(String.format("Illegal leading minus sign " + 917 "on unsigned string %s.", s.subSequence(start, start + len))); 918 } else { 919 if (len <= 12 || // Long.MAX_VALUE in Character.MAX_RADIX is 13 digits 920 (radix == 10 && len <= 18) ) { // Long.MAX_VALUE in base 10 is 19 digits 921 return parseLong(s, radix, start, start + len); 922 } 923 924 // No need for range checks on end due to testing above. 925 long first = parseLong(s, radix, start, start + len - 1); 926 int second = Character.digit(s.charAt(start + len - 1), radix); 927 if (second < 0) { 928 throw new NumberFormatException("Bad digit at end of " + 929 s.subSequence(start, start + len)); 930 } 931 long result = first * radix + second; 932 933 /* 934 * Test leftmost bits of multiprecision extension of first*radix 935 * for overflow. The number of bits needed is defined by 936 * GUARD_BIT = ceil(log2(Character.MAX_RADIX)) + 1 = 7. Then 937 * int guard = radix*(int)(first >>> (64 - GUARD_BIT)) and 938 * overflow is tested by splitting guard in the ranges 939 * guard < 92, 92 <= guard < 128, and 128 <= guard, where 940 * 92 = 128 - Character.MAX_RADIX. Note that guard cannot take 941 * on a value which does not include a prime factor in the legal 942 * radix range. 943 */ 944 int guard = radix * (int) (first >>> 57); 945 if (guard >= 128 || 946 (result >= 0 && guard >= 128 - Character.MAX_RADIX)) { 947 /* 948 * For purposes of exposition, the programmatic statements 949 * below should be taken to be multi-precision, i.e., not 950 * subject to overflow. 951 * 952 * A) Condition guard >= 128: 953 * If guard >= 128 then first*radix >= 2^7 * 2^57 = 2^64 954 * hence always overflow. 955 * 956 * B) Condition guard < 92: 957 * Define left7 = first >>> 57. 958 * Given first = (left7 * 2^57) + (first & (2^57 - 1)) then 959 * result <= (radix*left7)*2^57 + radix*(2^57 - 1) + second. 960 * Thus if radix*left7 < 92, radix <= 36, and second < 36, 961 * then result < 92*2^57 + 36*(2^57 - 1) + 36 = 2^64 hence 962 * never overflow. 963 * 964 * C) Condition 92 <= guard < 128: 965 * first*radix + second >= radix*left7*2^57 + second 966 * so that first*radix + second >= 92*2^57 + 0 > 2^63 967 * 968 * D) Condition guard < 128: 969 * radix*first <= (radix*left7) * 2^57 + radix*(2^57 - 1) 970 * so 971 * radix*first + second <= (radix*left7) * 2^57 + radix*(2^57 - 1) + 36 972 * thus 973 * radix*first + second < 128 * 2^57 + 36*2^57 - radix + 36 974 * whence 975 * radix*first + second < 2^64 + 2^6*2^57 = 2^64 + 2^63 976 * 977 * E) Conditions C, D, and result >= 0: 978 * C and D combined imply the mathematical result 979 * 2^63 < first*radix + second < 2^64 + 2^63. The lower 980 * bound is therefore negative as a signed long, but the 981 * upper bound is too small to overflow again after the 982 * signed long overflows to positive above 2^64 - 1. Hence 983 * result >= 0 implies overflow given C and D. 984 */ 985 throw new NumberFormatException(String.format("String value %s exceeds " + 986 "range of unsigned long.", s.subSequence(start, start + len))); 987 } 988 return result; 989 } 990 } else { 991 throw NumberFormatException.forInputString(""); 992 } 993 } 994 995 /** 996 * Parses the string argument as an unsigned decimal {@code long}. The 997 * characters in the string must all be decimal digits, except 998 * that the first character may be an an ASCII plus sign {@code 999 * '+'} ({@code '\u005Cu002B'}). The resulting integer value 1000 * is returned, exactly as if the argument and the radix 10 were 1001 * given as arguments to the {@link 1002 * #parseUnsignedLong(java.lang.String, int)} method. 1003 * 1004 * @param s a {@code String} containing the unsigned {@code long} 1005 * representation to be parsed 1006 * @return the unsigned {@code long} value represented by the decimal string argument 1007 * @throws NumberFormatException if the string does not contain a 1008 * parsable unsigned integer. 1009 * @since 1.8 1010 */ 1011 public static long parseUnsignedLong(String s) throws NumberFormatException { 1012 return parseUnsignedLong(s, 10); 1013 } 1014 1015 /** 1016 * Returns a {@code Long} object holding the value 1017 * extracted from the specified {@code String} when parsed 1018 * with the radix given by the second argument. The first 1019 * argument is interpreted as representing a signed 1020 * {@code long} in the radix specified by the second 1021 * argument, exactly as if the arguments were given to the {@link 1022 * #parseLong(java.lang.String, int)} method. The result is a 1023 * {@code Long} object that represents the {@code long} 1024 * value specified by the string. 1025 * 1026 * <p>In other words, this method returns a {@code Long} object equal 1027 * to the value of: 1028 * 1029 * <blockquote> 1030 * {@code new Long(Long.parseLong(s, radix))} 1031 * </blockquote> 1032 * 1033 * @param s the string to be parsed 1034 * @param radix the radix to be used in interpreting {@code s} 1035 * @return a {@code Long} object holding the value 1036 * represented by the string argument in the specified 1037 * radix. 1038 * @throws NumberFormatException If the {@code String} does not 1039 * contain a parsable {@code long}. 1040 */ 1041 public static Long valueOf(String s, int radix) throws NumberFormatException { 1042 return Long.valueOf(parseLong(s, radix)); 1043 } 1044 1045 /** 1046 * Returns a {@code Long} object holding the value 1047 * of the specified {@code String}. The argument is 1048 * interpreted as representing a signed decimal {@code long}, 1049 * exactly as if the argument were given to the {@link 1050 * #parseLong(java.lang.String)} method. The result is a 1051 * {@code Long} object that represents the integer value 1052 * specified by the string. 1053 * 1054 * <p>In other words, this method returns a {@code Long} object 1055 * equal to the value of: 1056 * 1057 * <blockquote> 1058 * {@code new Long(Long.parseLong(s))} 1059 * </blockquote> 1060 * 1061 * @param s the string to be parsed. 1062 * @return a {@code Long} object holding the value 1063 * represented by the string argument. 1064 * @throws NumberFormatException If the string cannot be parsed 1065 * as a {@code long}. 1066 */ 1067 public static Long valueOf(String s) throws NumberFormatException 1068 { 1069 return Long.valueOf(parseLong(s, 10)); 1070 } 1071 1072 private static class LongCache { 1073 private LongCache(){} 1074 1075 static final Long cache[] = new Long[-(-128) + 127 + 1]; 1076 1077 static { 1078 for(int i = 0; i < cache.length; i++) 1079 cache[i] = new Long(i - 128); 1080 } 1081 } 1082 1083 /** 1084 * Returns a {@code Long} instance representing the specified 1085 * {@code long} value. 1086 * If a new {@code Long} instance is not required, this method 1087 * should generally be used in preference to the constructor 1088 * {@link #Long(long)}, as this method is likely to yield 1089 * significantly better space and time performance by caching 1090 * frequently requested values. 1091 * 1092 * Note that unlike the {@linkplain Integer#valueOf(int) 1093 * corresponding method} in the {@code Integer} class, this method 1094 * is <em>not</em> required to cache values within a particular 1095 * range. 1096 * 1097 * @param l a long value. 1098 * @return a {@code Long} instance representing {@code l}. 1099 * @since 1.5 1100 */ 1101 public static Long valueOf(long l) { 1102 final int offset = 128; 1103 if (l >= -128 && l <= 127) { // will cache 1104 return LongCache.cache[(int)l + offset]; 1105 } 1106 return new Long(l); 1107 } 1108 1109 /** 1110 * Decodes a {@code String} into a {@code Long}. 1111 * Accepts decimal, hexadecimal, and octal numbers given by the 1112 * following grammar: 1113 * 1114 * <blockquote> 1115 * <dl> 1116 * <dt><i>DecodableString:</i> 1117 * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i> 1118 * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i> 1119 * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i> 1120 * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i> 1121 * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i> 1122 * 1123 * <dt><i>Sign:</i> 1124 * <dd>{@code -} 1125 * <dd>{@code +} 1126 * </dl> 1127 * </blockquote> 1128 * 1129 * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i> 1130 * are as defined in section 3.10.1 of 1131 * <cite>The Java™ Language Specification</cite>, 1132 * except that underscores are not accepted between digits. 1133 * 1134 * <p>The sequence of characters following an optional 1135 * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", 1136 * "{@code #}", or leading zero) is parsed as by the {@code 1137 * Long.parseLong} method with the indicated radix (10, 16, or 8). 1138 * This sequence of characters must represent a positive value or 1139 * a {@link NumberFormatException} will be thrown. The result is 1140 * negated if first character of the specified {@code String} is 1141 * the minus sign. No whitespace characters are permitted in the 1142 * {@code String}. 1143 * 1144 * @param nm the {@code String} to decode. 1145 * @return a {@code Long} object holding the {@code long} 1146 * value represented by {@code nm} 1147 * @throws NumberFormatException if the {@code String} does not 1148 * contain a parsable {@code long}. 1149 * @see java.lang.Long#parseLong(String, int) 1150 * @since 1.2 1151 */ 1152 public static Long decode(String nm) throws NumberFormatException { 1153 int radix = 10; 1154 int index = 0; 1155 boolean negative = false; 1156 Long result; 1157 1158 if (nm.length() == 0) 1159 throw new NumberFormatException("Zero length string"); 1160 char firstChar = nm.charAt(0); 1161 // Handle sign, if present 1162 if (firstChar == '-') { 1163 negative = true; 1164 index++; 1165 } else if (firstChar == '+') 1166 index++; 1167 1168 // Handle radix specifier, if present 1169 if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) { 1170 index += 2; 1171 radix = 16; 1172 } 1173 else if (nm.startsWith("#", index)) { 1174 index ++; 1175 radix = 16; 1176 } 1177 else if (nm.startsWith("0", index) && nm.length() > 1 + index) { 1178 index ++; 1179 radix = 8; 1180 } 1181 1182 if (nm.startsWith("-", index) || nm.startsWith("+", index)) 1183 throw new NumberFormatException("Sign character in wrong position"); 1184 1185 try { 1186 result = Long.valueOf(nm.substring(index), radix); 1187 result = negative ? Long.valueOf(-result.longValue()) : result; 1188 } catch (NumberFormatException e) { 1189 // If number is Long.MIN_VALUE, we'll end up here. The next line 1190 // handles this case, and causes any genuine format error to be 1191 // rethrown. 1192 String constant = negative ? ("-" + nm.substring(index)) 1193 : nm.substring(index); 1194 result = Long.valueOf(constant, radix); 1195 } 1196 return result; 1197 } 1198 1199 /** 1200 * The value of the {@code Long}. 1201 * 1202 * @serial 1203 */ 1204 private final long value; 1205 1206 /** 1207 * Constructs a newly allocated {@code Long} object that 1208 * represents the specified {@code long} argument. 1209 * 1210 * @param value the value to be represented by the 1211 * {@code Long} object. 1212 */ 1213 public Long(long value) { 1214 this.value = value; 1215 } 1216 1217 /** 1218 * Constructs a newly allocated {@code Long} object that 1219 * represents the {@code long} value indicated by the 1220 * {@code String} parameter. The string is converted to a 1221 * {@code long} value in exactly the manner used by the 1222 * {@code parseLong} method for radix 10. 1223 * 1224 * @param s the {@code String} to be converted to a 1225 * {@code Long}. 1226 * @throws NumberFormatException if the {@code String} does not 1227 * contain a parsable {@code long}. 1228 * @see java.lang.Long#parseLong(java.lang.String, int) 1229 */ 1230 public Long(String s) throws NumberFormatException { 1231 this.value = parseLong(s, 10); 1232 } 1233 1234 /** 1235 * Returns the value of this {@code Long} as a {@code byte} after 1236 * a narrowing primitive conversion. 1237 * @jls 5.1.3 Narrowing Primitive Conversions 1238 */ 1239 public byte byteValue() { 1240 return (byte)value; 1241 } 1242 1243 /** 1244 * Returns the value of this {@code Long} as a {@code short} after 1245 * a narrowing primitive conversion. 1246 * @jls 5.1.3 Narrowing Primitive Conversions 1247 */ 1248 public short shortValue() { 1249 return (short)value; 1250 } 1251 1252 /** 1253 * Returns the value of this {@code Long} as an {@code int} after 1254 * a narrowing primitive conversion. 1255 * @jls 5.1.3 Narrowing Primitive Conversions 1256 */ 1257 public int intValue() { 1258 return (int)value; 1259 } 1260 1261 /** 1262 * Returns the value of this {@code Long} as a 1263 * {@code long} value. 1264 */ 1265 public long longValue() { 1266 return value; 1267 } 1268 1269 /** 1270 * Returns the value of this {@code Long} as a {@code float} after 1271 * a widening primitive conversion. 1272 * @jls 5.1.2 Widening Primitive Conversions 1273 */ 1274 public float floatValue() { 1275 return (float)value; 1276 } 1277 1278 /** 1279 * Returns the value of this {@code Long} as a {@code double} 1280 * after a widening primitive conversion. 1281 * @jls 5.1.2 Widening Primitive Conversions 1282 */ 1283 public double doubleValue() { 1284 return (double)value; 1285 } 1286 1287 /** 1288 * Returns a {@code String} object representing this 1289 * {@code Long}'s value. The value is converted to signed 1290 * decimal representation and returned as a string, exactly as if 1291 * the {@code long} value were given as an argument to the 1292 * {@link java.lang.Long#toString(long)} method. 1293 * 1294 * @return a string representation of the value of this object in 1295 * base 10. 1296 */ 1297 public String toString() { 1298 return toString(value); 1299 } 1300 1301 /** 1302 * Returns a hash code for this {@code Long}. The result is 1303 * the exclusive OR of the two halves of the primitive 1304 * {@code long} value held by this {@code Long} 1305 * object. That is, the hashcode is the value of the expression: 1306 * 1307 * <blockquote> 1308 * {@code (int)(this.longValue()^(this.longValue()>>>32))} 1309 * </blockquote> 1310 * 1311 * @return a hash code value for this object. 1312 */ 1313 @Override 1314 public int hashCode() { 1315 return Long.hashCode(value); 1316 } 1317 1318 /** 1319 * Returns a hash code for a {@code long} value; compatible with 1320 * {@code Long.hashCode()}. 1321 * 1322 * @param value the value to hash 1323 * @return a hash code value for a {@code long} value. 1324 * @since 1.8 1325 */ 1326 public static int hashCode(long value) { 1327 return (int)(value ^ (value >>> 32)); 1328 } 1329 1330 /** 1331 * Compares this object to the specified object. The result is 1332 * {@code true} if and only if the argument is not 1333 * {@code null} and is a {@code Long} object that 1334 * contains the same {@code long} value as this object. 1335 * 1336 * @param obj the object to compare with. 1337 * @return {@code true} if the objects are the same; 1338 * {@code false} otherwise. 1339 */ 1340 public boolean equals(Object obj) { 1341 if (obj instanceof Long) { 1342 return value == ((Long)obj).longValue(); 1343 } 1344 return false; 1345 } 1346 1347 /** 1348 * Determines the {@code long} value of the system property 1349 * with the specified name. 1350 * 1351 * <p>The first argument is treated as the name of a system 1352 * property. System properties are accessible through the {@link 1353 * java.lang.System#getProperty(java.lang.String)} method. The 1354 * string value of this property is then interpreted as a {@code 1355 * long} value using the grammar supported by {@link Long#decode decode} 1356 * and a {@code Long} object representing this value is returned. 1357 * 1358 * <p>If there is no property with the specified name, if the 1359 * specified name is empty or {@code null}, or if the property 1360 * does not have the correct numeric format, then {@code null} is 1361 * returned. 1362 * 1363 * <p>In other words, this method returns a {@code Long} object 1364 * equal to the value of: 1365 * 1366 * <blockquote> 1367 * {@code getLong(nm, null)} 1368 * </blockquote> 1369 * 1370 * @param nm property name. 1371 * @return the {@code Long} value of the property. 1372 * @throws SecurityException for the same reasons as 1373 * {@link System#getProperty(String) System.getProperty} 1374 * @see java.lang.System#getProperty(java.lang.String) 1375 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1376 */ 1377 public static Long getLong(String nm) { 1378 return getLong(nm, null); 1379 } 1380 1381 /** 1382 * Determines the {@code long} value of the system property 1383 * with the specified name. 1384 * 1385 * <p>The first argument is treated as the name of a system 1386 * property. System properties are accessible through the {@link 1387 * java.lang.System#getProperty(java.lang.String)} method. The 1388 * string value of this property is then interpreted as a {@code 1389 * long} value using the grammar supported by {@link Long#decode decode} 1390 * and a {@code Long} object representing this value is returned. 1391 * 1392 * <p>The second argument is the default value. A {@code Long} object 1393 * that represents the value of the second argument is returned if there 1394 * is no property of the specified name, if the property does not have 1395 * the correct numeric format, or if the specified name is empty or null. 1396 * 1397 * <p>In other words, this method returns a {@code Long} object equal 1398 * to the value of: 1399 * 1400 * <blockquote> 1401 * {@code getLong(nm, new Long(val))} 1402 * </blockquote> 1403 * 1404 * but in practice it may be implemented in a manner such as: 1405 * 1406 * <blockquote><pre> 1407 * Long result = getLong(nm, null); 1408 * return (result == null) ? new Long(val) : result; 1409 * </pre></blockquote> 1410 * 1411 * to avoid the unnecessary allocation of a {@code Long} object when 1412 * the default value is not needed. 1413 * 1414 * @param nm property name. 1415 * @param val default value. 1416 * @return the {@code Long} value of the property. 1417 * @throws SecurityException for the same reasons as 1418 * {@link System#getProperty(String) System.getProperty} 1419 * @see java.lang.System#getProperty(java.lang.String) 1420 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1421 */ 1422 public static Long getLong(String nm, long val) { 1423 Long result = Long.getLong(nm, null); 1424 return (result == null) ? Long.valueOf(val) : result; 1425 } 1426 1427 /** 1428 * Returns the {@code long} value of the system property with 1429 * the specified name. The first argument is treated as the name 1430 * of a system property. System properties are accessible through 1431 * the {@link java.lang.System#getProperty(java.lang.String)} 1432 * method. The string value of this property is then interpreted 1433 * as a {@code long} value, as per the 1434 * {@link Long#decode decode} method, and a {@code Long} object 1435 * representing this value is returned; in summary: 1436 * 1437 * <ul> 1438 * <li>If the property value begins with the two ASCII characters 1439 * {@code 0x} or the ASCII character {@code #}, not followed by 1440 * a minus sign, then the rest of it is parsed as a hexadecimal integer 1441 * exactly as for the method {@link #valueOf(java.lang.String, int)} 1442 * with radix 16. 1443 * <li>If the property value begins with the ASCII character 1444 * {@code 0} followed by another character, it is parsed as 1445 * an octal integer exactly as by the method {@link 1446 * #valueOf(java.lang.String, int)} with radix 8. 1447 * <li>Otherwise the property value is parsed as a decimal 1448 * integer exactly as by the method 1449 * {@link #valueOf(java.lang.String, int)} with radix 10. 1450 * </ul> 1451 * 1452 * <p>Note that, in every case, neither {@code L} 1453 * ({@code '\u005Cu004C'}) nor {@code l} 1454 * ({@code '\u005Cu006C'}) is permitted to appear at the end 1455 * of the property value as a type indicator, as would be 1456 * permitted in Java programming language source code. 1457 * 1458 * <p>The second argument is the default value. The default value is 1459 * returned if there is no property of the specified name, if the 1460 * property does not have the correct numeric format, or if the 1461 * specified name is empty or {@code null}. 1462 * 1463 * @param nm property name. 1464 * @param val default value. 1465 * @return the {@code Long} value of the property. 1466 * @throws SecurityException for the same reasons as 1467 * {@link System#getProperty(String) System.getProperty} 1468 * @see System#getProperty(java.lang.String) 1469 * @see System#getProperty(java.lang.String, java.lang.String) 1470 */ 1471 public static Long getLong(String nm, Long val) { 1472 String v = null; 1473 try { 1474 v = System.getProperty(nm); 1475 } catch (IllegalArgumentException | NullPointerException e) { 1476 } 1477 if (v != null) { 1478 try { 1479 return Long.decode(v); 1480 } catch (NumberFormatException e) { 1481 } 1482 } 1483 return val; 1484 } 1485 1486 /** 1487 * Compares two {@code Long} objects numerically. 1488 * 1489 * @param anotherLong the {@code Long} to be compared. 1490 * @return the value {@code 0} if this {@code Long} is 1491 * equal to the argument {@code Long}; a value less than 1492 * {@code 0} if this {@code Long} is numerically less 1493 * than the argument {@code Long}; and a value greater 1494 * than {@code 0} if this {@code Long} is numerically 1495 * greater than the argument {@code Long} (signed 1496 * comparison). 1497 * @since 1.2 1498 */ 1499 public int compareTo(Long anotherLong) { 1500 return compare(this.value, anotherLong.value); 1501 } 1502 1503 /** 1504 * Compares two {@code long} values numerically. 1505 * The value returned is identical to what would be returned by: 1506 * <pre> 1507 * Long.valueOf(x).compareTo(Long.valueOf(y)) 1508 * </pre> 1509 * 1510 * @param x the first {@code long} to compare 1511 * @param y the second {@code long} to compare 1512 * @return the value {@code 0} if {@code x == y}; 1513 * a value less than {@code 0} if {@code x < y}; and 1514 * a value greater than {@code 0} if {@code x > y} 1515 * @since 1.7 1516 */ 1517 public static int compare(long x, long y) { 1518 return (x < y) ? -1 : ((x == y) ? 0 : 1); 1519 } 1520 1521 /** 1522 * Compares two {@code long} values numerically treating the values 1523 * as unsigned. 1524 * 1525 * @param x the first {@code long} to compare 1526 * @param y the second {@code long} to compare 1527 * @return the value {@code 0} if {@code x == y}; a value less 1528 * than {@code 0} if {@code x < y} as unsigned values; and 1529 * a value greater than {@code 0} if {@code x > y} as 1530 * unsigned values 1531 * @since 1.8 1532 */ 1533 public static int compareUnsigned(long x, long y) { 1534 return compare(x + MIN_VALUE, y + MIN_VALUE); 1535 } 1536 1537 1538 /** 1539 * Returns the unsigned quotient of dividing the first argument by 1540 * the second where each argument and the result is interpreted as 1541 * an unsigned value. 1542 * 1543 * <p>Note that in two's complement arithmetic, the three other 1544 * basic arithmetic operations of add, subtract, and multiply are 1545 * bit-wise identical if the two operands are regarded as both 1546 * being signed or both being unsigned. Therefore separate {@code 1547 * addUnsigned}, etc. methods are not provided. 1548 * 1549 * @param dividend the value to be divided 1550 * @param divisor the value doing the dividing 1551 * @return the unsigned quotient of the first argument divided by 1552 * the second argument 1553 * @see #remainderUnsigned 1554 * @since 1.8 1555 */ 1556 public static long divideUnsigned(long dividend, long divisor) { 1557 if (divisor < 0L) { // signed comparison 1558 // Answer must be 0 or 1 depending on relative magnitude 1559 // of dividend and divisor. 1560 return (compareUnsigned(dividend, divisor)) < 0 ? 0L :1L; 1561 } 1562 1563 if (dividend > 0) // Both inputs non-negative 1564 return dividend/divisor; 1565 else { 1566 /* 1567 * For simple code, leveraging BigInteger. Longer and faster 1568 * code written directly in terms of operations on longs is 1569 * possible; see "Hacker's Delight" for divide and remainder 1570 * algorithms. 1571 */ 1572 return toUnsignedBigInteger(dividend). 1573 divide(toUnsignedBigInteger(divisor)).longValue(); 1574 } 1575 } 1576 1577 /** 1578 * Returns the unsigned remainder from dividing the first argument 1579 * by the second where each argument and the result is interpreted 1580 * as an unsigned value. 1581 * 1582 * @param dividend the value to be divided 1583 * @param divisor the value doing the dividing 1584 * @return the unsigned remainder of the first argument divided by 1585 * the second argument 1586 * @see #divideUnsigned 1587 * @since 1.8 1588 */ 1589 public static long remainderUnsigned(long dividend, long divisor) { 1590 if (dividend > 0 && divisor > 0) { // signed comparisons 1591 return dividend % divisor; 1592 } else { 1593 if (compareUnsigned(dividend, divisor) < 0) // Avoid explicit check for 0 divisor 1594 return dividend; 1595 else 1596 return toUnsignedBigInteger(dividend). 1597 remainder(toUnsignedBigInteger(divisor)).longValue(); 1598 } 1599 } 1600 1601 // Bit Twiddling 1602 1603 /** 1604 * The number of bits used to represent a {@code long} value in two's 1605 * complement binary form. 1606 * 1607 * @since 1.5 1608 */ 1609 @Native public static final int SIZE = 64; 1610 1611 /** 1612 * The number of bytes used to represent a {@code long} value in two's 1613 * complement binary form. 1614 * 1615 * @since 1.8 1616 */ 1617 public static final int BYTES = SIZE / Byte.SIZE; 1618 1619 /** 1620 * Returns a {@code long} value with at most a single one-bit, in the 1621 * position of the highest-order ("leftmost") 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 highest one bit is to be computed 1627 * @return a {@code long} value with a single one-bit, in the position 1628 * of the highest-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 highestOneBit(long i) { 1633 // HD, Figure 3-1 1634 i |= (i >> 1); 1635 i |= (i >> 2); 1636 i |= (i >> 4); 1637 i |= (i >> 8); 1638 i |= (i >> 16); 1639 i |= (i >> 32); 1640 return i - (i >>> 1); 1641 } 1642 1643 /** 1644 * Returns a {@code long} value with at most a single one-bit, in the 1645 * position of the lowest-order ("rightmost") one-bit in the specified 1646 * {@code long} value. Returns zero if the specified value has no 1647 * one-bits in its two's complement binary representation, that is, if it 1648 * is equal to zero. 1649 * 1650 * @param i the value whose lowest one bit is to be computed 1651 * @return a {@code long} value with a single one-bit, in the position 1652 * of the lowest-order one-bit in the specified value, or zero if 1653 * the specified value is itself equal to zero. 1654 * @since 1.5 1655 */ 1656 public static long lowestOneBit(long i) { 1657 // HD, Section 2-1 1658 return i & -i; 1659 } 1660 1661 /** 1662 * Returns 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. Returns 64 if the 1665 * specified value has no one-bits in its two's complement representation, 1666 * in other words if it is equal to zero. 1667 * 1668 * <p>Note that this method is closely related to the logarithm base 2. 1669 * For all positive {@code long} values x: 1670 * <ul> 1671 * <li>floor(log<sub>2</sub>(x)) = {@code 63 - numberOfLeadingZeros(x)} 1672 * <li>ceil(log<sub>2</sub>(x)) = {@code 64 - numberOfLeadingZeros(x - 1)} 1673 * </ul> 1674 * 1675 * @param i the value whose number of leading zeros is to be computed 1676 * @return the number of zero bits preceding the highest-order 1677 * ("leftmost") one-bit in the two's complement binary representation 1678 * of the specified {@code long} value, or 64 if the value 1679 * is equal to zero. 1680 * @since 1.5 1681 */ 1682 public static int numberOfLeadingZeros(long i) { 1683 // HD, Figure 5-6 1684 if (i == 0) 1685 return 64; 1686 int n = 1; 1687 int x = (int)(i >>> 32); 1688 if (x == 0) { n += 32; x = (int)i; } 1689 if (x >>> 16 == 0) { n += 16; x <<= 16; } 1690 if (x >>> 24 == 0) { n += 8; x <<= 8; } 1691 if (x >>> 28 == 0) { n += 4; x <<= 4; } 1692 if (x >>> 30 == 0) { n += 2; x <<= 2; } 1693 n -= x >>> 31; 1694 return n; 1695 } 1696 1697 /** 1698 * Returns the number of zero bits following the lowest-order ("rightmost") 1699 * one-bit in the two's complement binary representation of the specified 1700 * {@code long} value. Returns 64 if the specified value has no 1701 * one-bits in its two's complement representation, in other words if it is 1702 * equal to zero. 1703 * 1704 * @param i the value whose number of trailing zeros is to be computed 1705 * @return the number of zero bits following the lowest-order ("rightmost") 1706 * one-bit in the two's complement binary representation of the 1707 * specified {@code long} value, or 64 if the value is equal 1708 * to zero. 1709 * @since 1.5 1710 */ 1711 public static int numberOfTrailingZeros(long i) { 1712 // HD, Figure 5-14 1713 int x, y; 1714 if (i == 0) return 64; 1715 int n = 63; 1716 y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32); 1717 y = x <<16; if (y != 0) { n = n -16; x = y; } 1718 y = x << 8; if (y != 0) { n = n - 8; x = y; } 1719 y = x << 4; if (y != 0) { n = n - 4; x = y; } 1720 y = x << 2; if (y != 0) { n = n - 2; x = y; } 1721 return n - ((x << 1) >>> 31); 1722 } 1723 1724 /** 1725 * Returns the number of one-bits in the two's complement binary 1726 * representation of the specified {@code long} value. This function is 1727 * sometimes referred to as the <i>population count</i>. 1728 * 1729 * @param i the value whose bits are to be counted 1730 * @return the number of one-bits in the two's complement binary 1731 * representation of the specified {@code long} value. 1732 * @since 1.5 1733 */ 1734 public static int bitCount(long i) { 1735 // HD, Figure 5-14 1736 i = i - ((i >>> 1) & 0x5555555555555555L); 1737 i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L); 1738 i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL; 1739 i = i + (i >>> 8); 1740 i = i + (i >>> 16); 1741 i = i + (i >>> 32); 1742 return (int)i & 0x7f; 1743 } 1744 1745 /** 1746 * Returns the value obtained by rotating the two's complement binary 1747 * representation of the specified {@code long} value left by the 1748 * specified number of bits. (Bits shifted out of the left hand, or 1749 * high-order, side reenter on the right, or low-order.) 1750 * 1751 * <p>Note that left rotation with a negative distance is equivalent to 1752 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(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 rotateLeft(val, 1756 * distance) == rotateLeft(val, distance & 0x3F)}. 1757 * 1758 * @param i the value whose bits are to be rotated left 1759 * @param distance the number of bit positions to rotate left 1760 * @return the value obtained by rotating the two's complement binary 1761 * representation of the specified {@code long} value left by the 1762 * specified number of bits. 1763 * @since 1.5 1764 */ 1765 public static long rotateLeft(long i, int distance) { 1766 return (i << distance) | (i >>> -distance); 1767 } 1768 1769 /** 1770 * Returns the value obtained by rotating the two's complement binary 1771 * representation of the specified {@code long} value right by the 1772 * specified number of bits. (Bits shifted out of the right hand, or 1773 * low-order, side reenter on the left, or high-order.) 1774 * 1775 * <p>Note that right rotation with a negative distance is equivalent to 1776 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val, 1777 * distance)}. Note also that rotation by any multiple of 64 is a 1778 * no-op, so all but the last six bits of the rotation distance can be 1779 * ignored, even if the distance is negative: {@code rotateRight(val, 1780 * distance) == rotateRight(val, distance & 0x3F)}. 1781 * 1782 * @param i the value whose bits are to be rotated right 1783 * @param distance the number of bit positions to rotate right 1784 * @return the value obtained by rotating the two's complement binary 1785 * representation of the specified {@code long} value right by the 1786 * specified number of bits. 1787 * @since 1.5 1788 */ 1789 public static long rotateRight(long i, int distance) { 1790 return (i >>> distance) | (i << -distance); 1791 } 1792 1793 /** 1794 * Returns the value obtained by reversing the order of the bits in the 1795 * two's complement binary representation of the specified {@code long} 1796 * value. 1797 * 1798 * @param i the value to be reversed 1799 * @return the value obtained by reversing order of the bits in the 1800 * specified {@code long} value. 1801 * @since 1.5 1802 */ 1803 public static long reverse(long i) { 1804 // HD, Figure 7-1 1805 i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L; 1806 i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L; 1807 i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL; 1808 i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL; 1809 i = (i << 48) | ((i & 0xffff0000L) << 16) | 1810 ((i >>> 16) & 0xffff0000L) | (i >>> 48); 1811 return i; 1812 } 1813 1814 /** 1815 * Returns the signum function of the specified {@code long} value. (The 1816 * return value is -1 if the specified value is negative; 0 if the 1817 * specified value is zero; and 1 if the specified value is positive.) 1818 * 1819 * @param i the value whose signum is to be computed 1820 * @return the signum function of the specified {@code long} value. 1821 * @since 1.5 1822 */ 1823 public static int signum(long i) { 1824 // HD, Section 2-7 1825 return (int) ((i >> 63) | (-i >>> 63)); 1826 } 1827 1828 /** 1829 * Returns the value obtained by reversing the order of the bytes in the 1830 * two's complement representation of the specified {@code long} value. 1831 * 1832 * @param i the value whose bytes are to be reversed 1833 * @return the value obtained by reversing the bytes in the specified 1834 * {@code long} value. 1835 * @since 1.5 1836 */ 1837 public static long reverseBytes(long i) { 1838 i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL; 1839 return (i << 48) | ((i & 0xffff0000L) << 16) | 1840 ((i >>> 16) & 0xffff0000L) | (i >>> 48); 1841 } 1842 1843 /** 1844 * Adds two {@code long} values together as per the + operator. 1845 * 1846 * @param a the first operand 1847 * @param b the second operand 1848 * @return the sum of {@code a} and {@code b} 1849 * @see java.util.function.BinaryOperator 1850 * @since 1.8 1851 */ 1852 public static long sum(long a, long b) { 1853 return a + b; 1854 } 1855 1856 /** 1857 * Returns the greater of two {@code long} values 1858 * as if by calling {@link Math#max(long, long) Math.max}. 1859 * 1860 * @param a the first operand 1861 * @param b the second operand 1862 * @return the greater of {@code a} and {@code b} 1863 * @see java.util.function.BinaryOperator 1864 * @since 1.8 1865 */ 1866 public static long max(long a, long b) { 1867 return Math.max(a, b); 1868 } 1869 1870 /** 1871 * Returns the smaller of two {@code long} values 1872 * as if by calling {@link Math#min(long, long) Math.min}. 1873 * 1874 * @param a the first operand 1875 * @param b the second operand 1876 * @return the smaller of {@code a} and {@code b} 1877 * @see java.util.function.BinaryOperator 1878 * @since 1.8 1879 */ 1880 public static long min(long a, long b) { 1881 return Math.min(a, b); 1882 } 1883 1884 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 1885 @Native private static final long serialVersionUID = 4290774380558885855L; 1886 }