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