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