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