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