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