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