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