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