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