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 if (compareUnsigned(result, first) < 0) { 704 /* 705 * The maximum unsigned value, (2^64)-1, takes at 706 * most one more digit to represent than the 707 * maximum signed value, (2^63)-1. Therefore, 708 * parsing (len - 1) digits will be appropriately 709 * in-range of the signed parsing. In other 710 * words, if parsing (len -1) digits overflows 711 * signed parsing, parsing len digits will 712 * certainly overflow unsigned parsing. 713 * 714 * The compareUnsigned check above catches 715 * situations where an unsigned overflow occurs 716 * incorporating the contribution of the final 717 * digit. 718 */ 719 throw new NumberFormatException(String.format("String value %s exceeds " + 720 "range of unsigned long.", s)); 721 } 722 return result; 723 } 724 } else { 725 throw NumberFormatException.forInputString(s); 726 } 727 } 728 729 /** 730 * Parses the string argument as an unsigned decimal {@code long}. The 731 * characters in the string must all be decimal digits, except 732 * that the first character may be an an ASCII plus sign {@code 733 * '+'} ({@code '\u005Cu002B'}). The resulting integer value 734 * is returned, exactly as if the argument and the radix 10 were 735 * given as arguments to the {@link 736 * #parseUnsignedLong(java.lang.String, int)} method. 737 * 738 * @param s a {@code String} containing the unsigned {@code long} 739 * representation to be parsed 740 * @return the unsigned {@code long} value represented by the decimal string argument 741 * @throws NumberFormatException if the string does not contain a 742 * parsable unsigned integer. 743 * @since 1.8 744 */ 745 public static long parseUnsignedLong(String s) throws NumberFormatException { 746 return parseUnsignedLong(s, 10); 747 } 748 749 /** 750 * Returns a {@code Long} object holding the value 751 * extracted from the specified {@code String} when parsed 752 * with the radix given by the second argument. The first 753 * argument is interpreted as representing a signed 754 * {@code long} in the radix specified by the second 755 * argument, exactly as if the arguments were given to the {@link 756 * #parseLong(java.lang.String, int)} method. The result is a 757 * {@code Long} object that represents the {@code long} 758 * value specified by the string. 759 * 760 * <p>In other words, this method returns a {@code Long} object equal 761 * to the value of: 762 * 763 * <blockquote> 764 * {@code new Long(Long.parseLong(s, radix))} 765 * </blockquote> 766 * 767 * @param s the string to be parsed 768 * @param radix the radix to be used in interpreting {@code s} 769 * @return a {@code Long} object holding the value 770 * represented by the string argument in the specified 771 * radix. 772 * @throws NumberFormatException If the {@code String} does not 773 * contain a parsable {@code long}. 774 */ 775 public static Long valueOf(String s, int radix) throws NumberFormatException { 776 return Long.valueOf(parseLong(s, radix)); 777 } 778 779 /** 780 * Returns a {@code Long} object holding the value 781 * of the specified {@code String}. The argument is 782 * interpreted as representing a signed decimal {@code long}, 783 * exactly as if the argument were given to the {@link 784 * #parseLong(java.lang.String)} method. The result is a 785 * {@code Long} object that represents the integer value 786 * specified by the string. 787 * 788 * <p>In other words, this method returns a {@code Long} object 789 * equal to the value of: 790 * 791 * <blockquote> 792 * {@code new Long(Long.parseLong(s))} 793 * </blockquote> 794 * 795 * @param s the string to be parsed. 796 * @return a {@code Long} object holding the value 797 * represented by the string argument. 798 * @throws NumberFormatException If the string cannot be parsed 799 * as a {@code long}. 800 */ 801 public static Long valueOf(String s) throws NumberFormatException 802 { 803 return Long.valueOf(parseLong(s, 10)); 804 } 805 806 private static class LongCache { 807 private LongCache(){} 808 809 static final Long cache[] = new Long[-(-128) + 127 + 1]; 810 811 static { 812 for(int i = 0; i < cache.length; i++) 813 cache[i] = new Long(i - 128); 814 } 815 } 816 817 /** 818 * Returns a {@code Long} instance representing the specified 819 * {@code long} value. 820 * If a new {@code Long} instance is not required, this method 821 * should generally be used in preference to the constructor 822 * {@link #Long(long)}, as this method is likely to yield 823 * significantly better space and time performance by caching 824 * frequently requested values. 825 * 826 * Note that unlike the {@linkplain Integer#valueOf(int) 827 * corresponding method} in the {@code Integer} class, this method 828 * is <em>not</em> required to cache values within a particular 829 * range. 830 * 831 * @param l a long value. 832 * @return a {@code Long} instance representing {@code l}. 833 * @since 1.5 834 */ 835 public static Long valueOf(long l) { 836 final int offset = 128; 837 if (l >= -128 && l <= 127) { // will cache 838 return LongCache.cache[(int)l + offset]; 839 } 840 return new Long(l); 841 } 842 843 /** 844 * Decodes a {@code String} into a {@code Long}. 845 * Accepts decimal, hexadecimal, and octal numbers given by the 846 * following grammar: 847 * 848 * <blockquote> 849 * <dl> 850 * <dt><i>DecodableString:</i> 851 * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i> 852 * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i> 853 * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i> 854 * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i> 855 * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i> 856 * 857 * <dt><i>Sign:</i> 858 * <dd>{@code -} 859 * <dd>{@code +} 860 * </dl> 861 * </blockquote> 862 * 863 * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i> 864 * are as defined in section 3.10.1 of 865 * <cite>The Java™ Language Specification</cite>, 866 * except that underscores are not accepted between digits. 867 * 868 * <p>The sequence of characters following an optional 869 * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", 870 * "{@code #}", or leading zero) is parsed as by the {@code 871 * Long.parseLong} method with the indicated radix (10, 16, or 8). 872 * This sequence of characters must represent a positive value or 873 * a {@link NumberFormatException} will be thrown. The result is 874 * negated if first character of the specified {@code String} is 875 * the minus sign. No whitespace characters are permitted in the 876 * {@code String}. 877 * 878 * @param nm the {@code String} to decode. 879 * @return a {@code Long} object holding the {@code long} 880 * value represented by {@code nm} 881 * @throws NumberFormatException if the {@code String} does not 882 * contain a parsable {@code long}. 883 * @see java.lang.Long#parseLong(String, int) 884 * @since 1.2 885 */ 886 public static Long decode(String nm) throws NumberFormatException { 887 int radix = 10; 888 int index = 0; 889 boolean negative = false; 890 Long result; 891 892 if (nm.length() == 0) 893 throw new NumberFormatException("Zero length string"); 894 char firstChar = nm.charAt(0); 895 // Handle sign, if present 896 if (firstChar == '-') { 897 negative = true; 898 index++; 899 } else if (firstChar == '+') 900 index++; 901 902 // Handle radix specifier, if present 903 if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) { 904 index += 2; 905 radix = 16; 906 } 907 else if (nm.startsWith("#", index)) { 908 index ++; 909 radix = 16; 910 } 911 else if (nm.startsWith("0", index) && nm.length() > 1 + index) { 912 index ++; 913 radix = 8; 914 } 915 916 if (nm.startsWith("-", index) || nm.startsWith("+", index)) 917 throw new NumberFormatException("Sign character in wrong position"); 918 919 try { 920 result = Long.valueOf(nm.substring(index), radix); 921 result = negative ? Long.valueOf(-result.longValue()) : result; 922 } catch (NumberFormatException e) { 923 // If number is Long.MIN_VALUE, we'll end up here. The next line 924 // handles this case, and causes any genuine format error to be 925 // rethrown. 926 String constant = negative ? ("-" + nm.substring(index)) 927 : nm.substring(index); 928 result = Long.valueOf(constant, radix); 929 } 930 return result; 931 } 932 933 /** 934 * The value of the {@code Long}. 935 * 936 * @serial 937 */ 938 private final long value; 939 940 /** 941 * Constructs a newly allocated {@code Long} object that 942 * represents the specified {@code long} argument. 943 * 944 * @param value the value to be represented by the 945 * {@code Long} object. 946 */ 947 public Long(long value) { 948 this.value = value; 949 } 950 951 /** 952 * Constructs a newly allocated {@code Long} object that 953 * represents the {@code long} value indicated by the 954 * {@code String} parameter. The string is converted to a 955 * {@code long} value in exactly the manner used by the 956 * {@code parseLong} method for radix 10. 957 * 958 * @param s the {@code String} to be converted to a 959 * {@code Long}. 960 * @throws NumberFormatException if the {@code String} does not 961 * contain a parsable {@code long}. 962 * @see java.lang.Long#parseLong(java.lang.String, int) 963 */ 964 public Long(String s) throws NumberFormatException { 965 this.value = parseLong(s, 10); 966 } 967 968 /** 969 * Returns the value of this {@code Long} as a {@code byte} after 970 * a narrowing primitive conversion. 971 * @jls 5.1.3 Narrowing Primitive Conversions 972 */ 973 public byte byteValue() { 974 return (byte)value; 975 } 976 977 /** 978 * Returns the value of this {@code Long} as a {@code short} after 979 * a narrowing primitive conversion. 980 * @jls 5.1.3 Narrowing Primitive Conversions 981 */ 982 public short shortValue() { 983 return (short)value; 984 } 985 986 /** 987 * Returns the value of this {@code Long} as an {@code int} after 988 * a narrowing primitive conversion. 989 * @jls 5.1.3 Narrowing Primitive Conversions 990 */ 991 public int intValue() { 992 return (int)value; 993 } 994 995 /** 996 * Returns the value of this {@code Long} as a 997 * {@code long} value. 998 */ 999 public long longValue() { 1000 return value; 1001 } 1002 1003 /** 1004 * Returns the value of this {@code Long} as a {@code float} after 1005 * a widening primitive conversion. 1006 * @jls 5.1.2 Widening Primitive Conversions 1007 */ 1008 public float floatValue() { 1009 return (float)value; 1010 } 1011 1012 /** 1013 * Returns the value of this {@code Long} as a {@code double} 1014 * after a widening primitive conversion. 1015 * @jls 5.1.2 Widening Primitive Conversions 1016 */ 1017 public double doubleValue() { 1018 return (double)value; 1019 } 1020 1021 /** 1022 * Returns a {@code String} object representing this 1023 * {@code Long}'s value. The value is converted to signed 1024 * decimal representation and returned as a string, exactly as if 1025 * the {@code long} value were given as an argument to the 1026 * {@link java.lang.Long#toString(long)} method. 1027 * 1028 * @return a string representation of the value of this object in 1029 * base 10. 1030 */ 1031 public String toString() { 1032 return toString(value); 1033 } 1034 1035 /** 1036 * Returns a hash code for this {@code Long}. The result is 1037 * the exclusive OR of the two halves of the primitive 1038 * {@code long} value held by this {@code Long} 1039 * object. That is, the hashcode is the value of the expression: 1040 * 1041 * <blockquote> 1042 * {@code (int)(this.longValue()^(this.longValue()>>>32))} 1043 * </blockquote> 1044 * 1045 * @return a hash code value for this object. 1046 */ 1047 @Override 1048 public int hashCode() { 1049 return Long.hashCode(value); 1050 } 1051 1052 /** 1053 * Returns a hash code for a {@code long} value; compatible with 1054 * {@code Long.hashCode()}. 1055 * 1056 * @param value the value to hash 1057 * @return a hash code value for a {@code long} value. 1058 * @since 1.8 1059 */ 1060 public static int hashCode(long value) { 1061 return (int)(value ^ (value >>> 32)); 1062 } 1063 1064 /** 1065 * Compares this object to the specified object. The result is 1066 * {@code true} if and only if the argument is not 1067 * {@code null} and is a {@code Long} object that 1068 * contains the same {@code long} value as this object. 1069 * 1070 * @param obj the object to compare with. 1071 * @return {@code true} if the objects are the same; 1072 * {@code false} otherwise. 1073 */ 1074 public boolean equals(Object obj) { 1075 if (obj instanceof Long) { 1076 return value == ((Long)obj).longValue(); 1077 } 1078 return false; 1079 } 1080 1081 /** 1082 * Determines the {@code long} value of the system property 1083 * with the specified name. 1084 * 1085 * <p>The first argument is treated as the name of a system 1086 * property. System properties are accessible through the {@link 1087 * java.lang.System#getProperty(java.lang.String)} method. The 1088 * string value of this property is then interpreted as a {@code 1089 * long} value using the grammar supported by {@link Long#decode decode} 1090 * and a {@code Long} object representing this value is returned. 1091 * 1092 * <p>If there is no property with the specified name, if the 1093 * specified name is empty or {@code null}, or if the property 1094 * does not have the correct numeric format, then {@code null} is 1095 * returned. 1096 * 1097 * <p>In other words, this method returns a {@code Long} object 1098 * equal to the value of: 1099 * 1100 * <blockquote> 1101 * {@code getLong(nm, null)} 1102 * </blockquote> 1103 * 1104 * @param nm property name. 1105 * @return the {@code Long} value of the property. 1106 * @throws SecurityException for the same reasons as 1107 * {@link System#getProperty(String) System.getProperty} 1108 * @see java.lang.System#getProperty(java.lang.String) 1109 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1110 */ 1111 public static Long getLong(String nm) { 1112 return getLong(nm, null); 1113 } 1114 1115 /** 1116 * Determines the {@code long} value of the system property 1117 * with the specified name. 1118 * 1119 * <p>The first argument is treated as the name of a system 1120 * property. System properties are accessible through the {@link 1121 * java.lang.System#getProperty(java.lang.String)} method. The 1122 * string value of this property is then interpreted as a {@code 1123 * long} value using the grammar supported by {@link Long#decode decode} 1124 * and a {@code Long} object representing this value is returned. 1125 * 1126 * <p>The second argument is the default value. A {@code Long} object 1127 * that represents the value of the second argument is returned if there 1128 * is no property of the specified name, if the property does not have 1129 * the correct numeric format, or if the specified name is empty or null. 1130 * 1131 * <p>In other words, this method returns a {@code Long} object equal 1132 * to the value of: 1133 * 1134 * <blockquote> 1135 * {@code getLong(nm, new Long(val))} 1136 * </blockquote> 1137 * 1138 * but in practice it may be implemented in a manner such as: 1139 * 1140 * <blockquote><pre> 1141 * Long result = getLong(nm, null); 1142 * return (result == null) ? new Long(val) : result; 1143 * </pre></blockquote> 1144 * 1145 * to avoid the unnecessary allocation of a {@code Long} object when 1146 * the default value is not needed. 1147 * 1148 * @param nm property name. 1149 * @param val default value. 1150 * @return the {@code Long} value of the property. 1151 * @throws SecurityException for the same reasons as 1152 * {@link System#getProperty(String) System.getProperty} 1153 * @see java.lang.System#getProperty(java.lang.String) 1154 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1155 */ 1156 public static Long getLong(String nm, long val) { 1157 Long result = Long.getLong(nm, null); 1158 return (result == null) ? Long.valueOf(val) : result; 1159 } 1160 1161 /** 1162 * Returns the {@code long} value of the system property with 1163 * the specified name. The first argument is treated as the name 1164 * of a system property. System properties are accessible through 1165 * the {@link java.lang.System#getProperty(java.lang.String)} 1166 * method. The string value of this property is then interpreted 1167 * as a {@code long} value, as per the 1168 * {@link Long#decode decode} method, and a {@code Long} object 1169 * representing this value is returned; in summary: 1170 * 1171 * <ul> 1172 * <li>If the property value begins with the two ASCII characters 1173 * {@code 0x} or the ASCII character {@code #}, not followed by 1174 * a minus sign, then the rest of it is parsed as a hexadecimal integer 1175 * exactly as for the method {@link #valueOf(java.lang.String, int)} 1176 * with radix 16. 1177 * <li>If the property value begins with the ASCII character 1178 * {@code 0} followed by another character, it is parsed as 1179 * an octal integer exactly as by the method {@link 1180 * #valueOf(java.lang.String, int)} with radix 8. 1181 * <li>Otherwise the property value is parsed as a decimal 1182 * integer exactly as by the method 1183 * {@link #valueOf(java.lang.String, int)} with radix 10. 1184 * </ul> 1185 * 1186 * <p>Note that, in every case, neither {@code L} 1187 * ({@code '\u005Cu004C'}) nor {@code l} 1188 * ({@code '\u005Cu006C'}) is permitted to appear at the end 1189 * of the property value as a type indicator, as would be 1190 * permitted in Java programming language source code. 1191 * 1192 * <p>The second argument is the default value. The default value is 1193 * returned if there is no property of the specified name, if the 1194 * property does not have the correct numeric format, or if the 1195 * specified name is empty or {@code null}. 1196 * 1197 * @param nm property name. 1198 * @param val default value. 1199 * @return the {@code Long} value of the property. 1200 * @throws SecurityException for the same reasons as 1201 * {@link System#getProperty(String) System.getProperty} 1202 * @see System#getProperty(java.lang.String) 1203 * @see System#getProperty(java.lang.String, java.lang.String) 1204 */ 1205 public static Long getLong(String nm, Long val) { 1206 String v = null; 1207 try { 1208 v = System.getProperty(nm); 1209 } catch (IllegalArgumentException | NullPointerException e) { 1210 } 1211 if (v != null) { 1212 try { 1213 return Long.decode(v); 1214 } catch (NumberFormatException e) { 1215 } 1216 } 1217 return val; 1218 } 1219 1220 /** 1221 * Compares two {@code Long} objects numerically. 1222 * 1223 * @param anotherLong the {@code Long} to be compared. 1224 * @return the value {@code 0} if this {@code Long} is 1225 * equal to the argument {@code Long}; a value less than 1226 * {@code 0} if this {@code Long} is numerically less 1227 * than the argument {@code Long}; and a value greater 1228 * than {@code 0} if this {@code Long} is numerically 1229 * greater than the argument {@code Long} (signed 1230 * comparison). 1231 * @since 1.2 1232 */ 1233 public int compareTo(Long anotherLong) { 1234 return compare(this.value, anotherLong.value); 1235 } 1236 1237 /** 1238 * Compares two {@code long} values numerically. 1239 * The value returned is identical to what would be returned by: 1240 * <pre> 1241 * Long.valueOf(x).compareTo(Long.valueOf(y)) 1242 * </pre> 1243 * 1244 * @param x the first {@code long} to compare 1245 * @param y the second {@code long} to compare 1246 * @return the value {@code 0} if {@code x == y}; 1247 * a value less than {@code 0} if {@code x < y}; and 1248 * a value greater than {@code 0} if {@code x > y} 1249 * @since 1.7 1250 */ 1251 public static int compare(long x, long y) { 1252 return (x < y) ? -1 : ((x == y) ? 0 : 1); 1253 } 1254 1255 /** 1256 * Compares two {@code long} values numerically treating the values 1257 * as unsigned. 1258 * 1259 * @param x the first {@code long} to compare 1260 * @param y the second {@code long} to compare 1261 * @return the value {@code 0} if {@code x == y}; a value less 1262 * than {@code 0} if {@code x < y} as unsigned values; and 1263 * a value greater than {@code 0} if {@code x > y} as 1264 * unsigned values 1265 * @since 1.8 1266 */ 1267 public static int compareUnsigned(long x, long y) { 1268 return compare(x + MIN_VALUE, y + MIN_VALUE); 1269 } 1270 1271 1272 /** 1273 * Returns the unsigned quotient of dividing the first argument by 1274 * the second where each argument and the result is interpreted as 1275 * an unsigned value. 1276 * 1277 * <p>Note that in two's complement arithmetic, the three other 1278 * basic arithmetic operations of add, subtract, and multiply are 1279 * bit-wise identical if the two operands are regarded as both 1280 * being signed or both being unsigned. Therefore separate {@code 1281 * addUnsigned}, etc. methods are not provided. 1282 * 1283 * @param dividend the value to be divided 1284 * @param divisor the value doing the dividing 1285 * @return the unsigned quotient of the first argument divided by 1286 * the second argument 1287 * @see #remainderUnsigned 1288 * @since 1.8 1289 */ 1290 public static long divideUnsigned(long dividend, long divisor) { 1291 if (divisor < 0L) { // signed comparison 1292 // Answer must be 0 or 1 depending on relative magnitude 1293 // of dividend and divisor. 1294 return (compareUnsigned(dividend, divisor)) < 0 ? 0L :1L; 1295 } 1296 1297 if (dividend > 0) // Both inputs non-negative 1298 return dividend/divisor; 1299 else { 1300 /* 1301 * For simple code, leveraging BigInteger. Longer and faster 1302 * code written directly in terms of operations on longs is 1303 * possible; see "Hacker's Delight" for divide and remainder 1304 * algorithms. 1305 */ 1306 return toUnsignedBigInteger(dividend). 1307 divide(toUnsignedBigInteger(divisor)).longValue(); 1308 } 1309 } 1310 1311 /** 1312 * Returns the unsigned remainder from dividing the first argument 1313 * by the second where each argument and the result is interpreted 1314 * as an unsigned value. 1315 * 1316 * @param dividend the value to be divided 1317 * @param divisor the value doing the dividing 1318 * @return the unsigned remainder of the first argument divided by 1319 * the second argument 1320 * @see #divideUnsigned 1321 * @since 1.8 1322 */ 1323 public static long remainderUnsigned(long dividend, long divisor) { 1324 if (dividend > 0 && divisor > 0) { // signed comparisons 1325 return dividend % divisor; 1326 } else { 1327 if (compareUnsigned(dividend, divisor) < 0) // Avoid explicit check for 0 divisor 1328 return dividend; 1329 else 1330 return toUnsignedBigInteger(dividend). 1331 remainder(toUnsignedBigInteger(divisor)).longValue(); 1332 } 1333 } 1334 1335 // Bit Twiddling 1336 1337 /** 1338 * The number of bits used to represent a {@code long} value in two's 1339 * complement binary form. 1340 * 1341 * @since 1.5 1342 */ 1343 @Native public static final int SIZE = 64; 1344 1345 /** 1346 * The number of bytes used to represent a {@code long} value in two's 1347 * complement binary form. 1348 * 1349 * @since 1.8 1350 */ 1351 public static final int BYTES = SIZE / Byte.SIZE; 1352 1353 /** 1354 * Returns a {@code long} value with at most a single one-bit, in the 1355 * position of the highest-order ("leftmost") one-bit in the specified 1356 * {@code long} value. Returns zero if the specified value has no 1357 * one-bits in its two's complement binary representation, that is, if it 1358 * is equal to zero. 1359 * 1360 * @param i the value whose highest one bit is to be computed 1361 * @return a {@code long} value with a single one-bit, in the position 1362 * of the highest-order one-bit in the specified value, or zero if 1363 * the specified value is itself equal to zero. 1364 * @since 1.5 1365 */ 1366 public static long highestOneBit(long i) { 1367 // HD, Figure 3-1 1368 i |= (i >> 1); 1369 i |= (i >> 2); 1370 i |= (i >> 4); 1371 i |= (i >> 8); 1372 i |= (i >> 16); 1373 i |= (i >> 32); 1374 return i - (i >>> 1); 1375 } 1376 1377 /** 1378 * Returns a {@code long} value with at most a single one-bit, in the 1379 * position of the lowest-order ("rightmost") one-bit in the specified 1380 * {@code long} value. Returns zero if the specified value has no 1381 * one-bits in its two's complement binary representation, that is, if it 1382 * is equal to zero. 1383 * 1384 * @param i the value whose lowest one bit is to be computed 1385 * @return a {@code long} value with a single one-bit, in the position 1386 * of the lowest-order one-bit in the specified value, or zero if 1387 * the specified value is itself equal to zero. 1388 * @since 1.5 1389 */ 1390 public static long lowestOneBit(long i) { 1391 // HD, Section 2-1 1392 return i & -i; 1393 } 1394 1395 /** 1396 * Returns the number of zero bits preceding the highest-order 1397 * ("leftmost") one-bit in the two's complement binary representation 1398 * of the specified {@code long} value. Returns 64 if the 1399 * specified value has no one-bits in its two's complement representation, 1400 * in other words if it is equal to zero. 1401 * 1402 * <p>Note that this method is closely related to the logarithm base 2. 1403 * For all positive {@code long} values x: 1404 * <ul> 1405 * <li>floor(log<sub>2</sub>(x)) = {@code 63 - numberOfLeadingZeros(x)} 1406 * <li>ceil(log<sub>2</sub>(x)) = {@code 64 - numberOfLeadingZeros(x - 1)} 1407 * </ul> 1408 * 1409 * @param i the value whose number of leading zeros is to be computed 1410 * @return the number of zero bits preceding the highest-order 1411 * ("leftmost") one-bit in the two's complement binary representation 1412 * of the specified {@code long} value, or 64 if the value 1413 * is equal to zero. 1414 * @since 1.5 1415 */ 1416 public static int numberOfLeadingZeros(long i) { 1417 // HD, Figure 5-6 1418 if (i == 0) 1419 return 64; 1420 int n = 1; 1421 int x = (int)(i >>> 32); 1422 if (x == 0) { n += 32; x = (int)i; } 1423 if (x >>> 16 == 0) { n += 16; x <<= 16; } 1424 if (x >>> 24 == 0) { n += 8; x <<= 8; } 1425 if (x >>> 28 == 0) { n += 4; x <<= 4; } 1426 if (x >>> 30 == 0) { n += 2; x <<= 2; } 1427 n -= x >>> 31; 1428 return n; 1429 } 1430 1431 /** 1432 * Returns the number of zero bits following the lowest-order ("rightmost") 1433 * one-bit in the two's complement binary representation of the specified 1434 * {@code long} value. Returns 64 if the specified value has no 1435 * one-bits in its two's complement representation, in other words if it is 1436 * equal to zero. 1437 * 1438 * @param i the value whose number of trailing zeros is to be computed 1439 * @return the number of zero bits following the lowest-order ("rightmost") 1440 * one-bit in the two's complement binary representation of the 1441 * specified {@code long} value, or 64 if the value is equal 1442 * to zero. 1443 * @since 1.5 1444 */ 1445 public static int numberOfTrailingZeros(long i) { 1446 // HD, Figure 5-14 1447 int x, y; 1448 if (i == 0) return 64; 1449 int n = 63; 1450 y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32); 1451 y = x <<16; if (y != 0) { n = n -16; x = y; } 1452 y = x << 8; if (y != 0) { n = n - 8; x = y; } 1453 y = x << 4; if (y != 0) { n = n - 4; x = y; } 1454 y = x << 2; if (y != 0) { n = n - 2; x = y; } 1455 return n - ((x << 1) >>> 31); 1456 } 1457 1458 /** 1459 * Returns the number of one-bits in the two's complement binary 1460 * representation of the specified {@code long} value. This function is 1461 * sometimes referred to as the <i>population count</i>. 1462 * 1463 * @param i the value whose bits are to be counted 1464 * @return the number of one-bits in the two's complement binary 1465 * representation of the specified {@code long} value. 1466 * @since 1.5 1467 */ 1468 public static int bitCount(long i) { 1469 // HD, Figure 5-14 1470 i = i - ((i >>> 1) & 0x5555555555555555L); 1471 i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L); 1472 i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL; 1473 i = i + (i >>> 8); 1474 i = i + (i >>> 16); 1475 i = i + (i >>> 32); 1476 return (int)i & 0x7f; 1477 } 1478 1479 /** 1480 * Returns the value obtained by rotating the two's complement binary 1481 * representation of the specified {@code long} value left by the 1482 * specified number of bits. (Bits shifted out of the left hand, or 1483 * high-order, side reenter on the right, or low-order.) 1484 * 1485 * <p>Note that left rotation with a negative distance is equivalent to 1486 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val, 1487 * distance)}. Note also that rotation by any multiple of 64 is a 1488 * no-op, so all but the last six bits of the rotation distance can be 1489 * ignored, even if the distance is negative: {@code rotateLeft(val, 1490 * distance) == rotateLeft(val, distance & 0x3F)}. 1491 * 1492 * @param i the value whose bits are to be rotated left 1493 * @param distance the number of bit positions to rotate left 1494 * @return the value obtained by rotating the two's complement binary 1495 * representation of the specified {@code long} value left by the 1496 * specified number of bits. 1497 * @since 1.5 1498 */ 1499 public static long rotateLeft(long i, int distance) { 1500 return (i << distance) | (i >>> -distance); 1501 } 1502 1503 /** 1504 * Returns the value obtained by rotating the two's complement binary 1505 * representation of the specified {@code long} value right by the 1506 * specified number of bits. (Bits shifted out of the right hand, or 1507 * low-order, side reenter on the left, or high-order.) 1508 * 1509 * <p>Note that right rotation with a negative distance is equivalent to 1510 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val, 1511 * distance)}. Note also that rotation by any multiple of 64 is a 1512 * no-op, so all but the last six bits of the rotation distance can be 1513 * ignored, even if the distance is negative: {@code rotateRight(val, 1514 * distance) == rotateRight(val, distance & 0x3F)}. 1515 * 1516 * @param i the value whose bits are to be rotated right 1517 * @param distance the number of bit positions to rotate right 1518 * @return the value obtained by rotating the two's complement binary 1519 * representation of the specified {@code long} value right by the 1520 * specified number of bits. 1521 * @since 1.5 1522 */ 1523 public static long rotateRight(long i, int distance) { 1524 return (i >>> distance) | (i << -distance); 1525 } 1526 1527 /** 1528 * Returns the value obtained by reversing the order of the bits in the 1529 * two's complement binary representation of the specified {@code long} 1530 * value. 1531 * 1532 * @param i the value to be reversed 1533 * @return the value obtained by reversing order of the bits in the 1534 * specified {@code long} value. 1535 * @since 1.5 1536 */ 1537 public static long reverse(long i) { 1538 // HD, Figure 7-1 1539 i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L; 1540 i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L; 1541 i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL; 1542 i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL; 1543 i = (i << 48) | ((i & 0xffff0000L) << 16) | 1544 ((i >>> 16) & 0xffff0000L) | (i >>> 48); 1545 return i; 1546 } 1547 1548 /** 1549 * Returns the signum function of the specified {@code long} value. (The 1550 * return value is -1 if the specified value is negative; 0 if the 1551 * specified value is zero; and 1 if the specified value is positive.) 1552 * 1553 * @param i the value whose signum is to be computed 1554 * @return the signum function of the specified {@code long} value. 1555 * @since 1.5 1556 */ 1557 public static int signum(long i) { 1558 // HD, Section 2-7 1559 return (int) ((i >> 63) | (-i >>> 63)); 1560 } 1561 1562 /** 1563 * Returns the value obtained by reversing the order of the bytes in the 1564 * two's complement representation of the specified {@code long} value. 1565 * 1566 * @param i the value whose bytes are to be reversed 1567 * @return the value obtained by reversing the bytes in the specified 1568 * {@code long} value. 1569 * @since 1.5 1570 */ 1571 public static long reverseBytes(long i) { 1572 i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL; 1573 return (i << 48) | ((i & 0xffff0000L) << 16) | 1574 ((i >>> 16) & 0xffff0000L) | (i >>> 48); 1575 } 1576 1577 /** 1578 * Adds two {@code long} values together as per the + operator. 1579 * 1580 * @param a the first operand 1581 * @param b the second operand 1582 * @return the sum of {@code a} and {@code b} 1583 * @see java.util.function.BinaryOperator 1584 * @since 1.8 1585 */ 1586 public static long sum(long a, long b) { 1587 return a + b; 1588 } 1589 1590 /** 1591 * Returns the greater of two {@code long} values 1592 * as if by calling {@link Math#max(long, long) Math.max}. 1593 * 1594 * @param a the first operand 1595 * @param b the second operand 1596 * @return the greater of {@code a} and {@code b} 1597 * @see java.util.function.BinaryOperator 1598 * @since 1.8 1599 */ 1600 public static long max(long a, long b) { 1601 return Math.max(a, b); 1602 } 1603 1604 /** 1605 * Returns the smaller of two {@code long} values 1606 * as if by calling {@link Math#min(long, long) Math.min}. 1607 * 1608 * @param a the first operand 1609 * @param b the second operand 1610 * @return the smaller of {@code a} and {@code b} 1611 * @see java.util.function.BinaryOperator 1612 * @since 1.8 1613 */ 1614 public static long min(long a, long b) { 1615 return Math.min(a, b); 1616 } 1617 1618 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 1619 @Native private static final long serialVersionUID = 4290774380558885855L; 1620 }