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