1 /* 2 * Copyright (c) 1994, 2023, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang; 27 28 import java.lang.annotation.Native; 29 import java.lang.invoke.MethodHandles; 30 import java.lang.constant.Constable; 31 import java.lang.constant.ConstantDesc; 32 import java.math.*; 33 import java.util.Objects; 34 import java.util.Optional; 35 36 import jdk.internal.misc.CDS; 37 import jdk.internal.vm.annotation.ForceInline; 38 import jdk.internal.vm.annotation.IntrinsicCandidate; 39 import jdk.internal.vm.annotation.Stable; 40 41 import static java.lang.Character.digit; 42 import static java.lang.String.COMPACT_STRINGS; 43 import static java.lang.String.LATIN1; 44 import static java.lang.String.UTF16; 45 46 /** 47 * The {@code Long} class wraps a value of the primitive type {@code 48 * long} in an object. An object of type {@code Long} contains a 49 * single field whose type is {@code long}. 50 * 51 * <p> In addition, this class provides several methods for converting 52 * a {@code long} to a {@code String} and a {@code String} to a {@code 53 * long}, as well as other constants and methods useful when dealing 54 * with a {@code long}. 55 * 56 * <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a> 57 * class; programmers should treat instances that are 58 * {@linkplain #equals(Object) equal} as interchangeable and should not 59 * use instances for synchronization, or unpredictable behavior may 60 * occur. For example, in a future release, synchronization may fail. 61 * 62 * <p>Implementation note: The implementations of the "bit twiddling" 63 * methods (such as {@link #highestOneBit(long) highestOneBit} and 64 * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are 65 * based on material from Henry S. Warren, Jr.'s <i>Hacker's 66 * Delight</i>, (Addison Wesley, 2002). 67 * 68 * @author Lee Boynton 69 * @author Arthur van Hoff 70 * @author Josh Bloch 71 * @author Joseph D. Darcy 72 * @since 1.0 73 */ 74 @jdk.internal.ValueBased 75 public final class Long extends Number 76 implements Comparable<Long>, Constable, ConstantDesc { 77 /** 78 * A constant holding the minimum value a {@code long} can 79 * have, -2<sup>63</sup>. 80 */ 81 @Native public static final long MIN_VALUE = 0x8000000000000000L; 82 83 /** 84 * A constant holding the maximum value a {@code long} can 85 * have, 2<sup>63</sup>-1. 86 */ 87 @Native public static final long MAX_VALUE = 0x7fffffffffffffffL; 88 89 /** 90 * The {@code Class} instance representing the primitive type 91 * {@code long}. 92 * 93 * @since 1.1 94 */ 95 @SuppressWarnings("unchecked") 96 public static final Class<Long> TYPE = (Class<Long>) Class.getPrimitiveClass("long"); 97 98 /** 99 * Returns a string representation of the first argument in the 100 * radix specified by the second argument. 101 * 102 * <p>If the radix is smaller than {@code Character.MIN_RADIX} 103 * or larger than {@code Character.MAX_RADIX}, then the radix 104 * {@code 10} is used instead. 105 * 106 * <p>If the first argument is negative, the first element of the 107 * result is the ASCII minus sign {@code '-'} 108 * ({@code '\u005Cu002d'}). If the first argument is not 109 * negative, no sign character appears in the result. 110 * 111 * <p>The remaining characters of the result represent the magnitude 112 * of the first argument. If the magnitude is zero, it is 113 * represented by a single zero character {@code '0'} 114 * ({@code '\u005Cu0030'}); otherwise, the first character of 115 * the representation of the magnitude will not be the zero 116 * character. The following ASCII characters are used as digits: 117 * 118 * <blockquote> 119 * {@code 0123456789abcdefghijklmnopqrstuvwxyz} 120 * </blockquote> 121 * 122 * These are {@code '\u005Cu0030'} through 123 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through 124 * {@code '\u005Cu007a'}. If {@code radix} is 125 * <var>N</var>, then the first <var>N</var> of these characters 126 * are used as radix-<var>N</var> digits in the order shown. Thus, 127 * the digits for hexadecimal (radix 16) are 128 * {@code 0123456789abcdef}. If uppercase letters are 129 * desired, the {@link java.lang.String#toUpperCase()} method may 130 * be called on the result: 131 * 132 * <blockquote> 133 * {@code Long.toString(n, 16).toUpperCase()} 134 * </blockquote> 135 * 136 * @param i a {@code long} to be converted to a string. 137 * @param radix the radix to use in the string representation. 138 * @return a string representation of the argument in the specified radix. 139 * @see java.lang.Character#MAX_RADIX 140 * @see java.lang.Character#MIN_RADIX 141 */ 142 public static String toString(long i, int radix) { 143 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) 144 radix = 10; 145 if (radix == 10) 146 return toString(i); 147 148 if (COMPACT_STRINGS) { 149 byte[] buf = new byte[65]; 150 int charPos = 64; 151 boolean negative = (i < 0); 152 153 if (!negative) { 154 i = -i; 155 } 156 157 while (i <= -radix) { 158 buf[charPos--] = (byte)Integer.digits[(int)(-(i % radix))]; 159 i = i / radix; 160 } 161 buf[charPos] = (byte)Integer.digits[(int)(-i)]; 162 163 if (negative) { 164 buf[--charPos] = '-'; 165 } 166 return StringLatin1.newString(buf, charPos, (65 - charPos)); 167 } 168 return toStringUTF16(i, radix); 169 } 170 171 private static String toStringUTF16(long i, int radix) { 172 byte[] buf = new byte[65 * 2]; 173 int charPos = 64; 174 boolean negative = (i < 0); 175 if (!negative) { 176 i = -i; 177 } 178 while (i <= -radix) { 179 StringUTF16.putChar(buf, charPos--, Integer.digits[(int)(-(i % radix))]); 180 i = i / radix; 181 } 182 StringUTF16.putChar(buf, charPos, Integer.digits[(int)(-i)]); 183 if (negative) { 184 StringUTF16.putChar(buf, --charPos, '-'); 185 } 186 return StringUTF16.newString(buf, charPos, (65 - charPos)); 187 } 188 189 /** 190 * Returns a string representation of the first argument as an 191 * unsigned integer value in the radix specified by the second 192 * argument. 193 * 194 * <p>If the radix is smaller than {@code Character.MIN_RADIX} 195 * or larger than {@code Character.MAX_RADIX}, then the radix 196 * {@code 10} is used instead. 197 * 198 * <p>Note that since the first argument is treated as an unsigned 199 * value, no leading sign character is printed. 200 * 201 * <p>If the magnitude is zero, it is represented by a single zero 202 * character {@code '0'} ({@code '\u005Cu0030'}); otherwise, 203 * the first character of the representation of the magnitude will 204 * not be the zero character. 205 * 206 * <p>The behavior of radixes and the characters used as digits 207 * are the same as {@link #toString(long, int) toString}. 208 * 209 * @param i an integer to be converted to an unsigned string. 210 * @param radix the radix to use in the string representation. 211 * @return an unsigned string representation of the argument in the specified radix. 212 * @see #toString(long, int) 213 * @since 1.8 214 */ 215 public static String toUnsignedString(long i, int radix) { 216 if (i >= 0) 217 return toString(i, radix); 218 else { 219 return switch (radix) { 220 case 2 -> toBinaryString(i); 221 case 4 -> toUnsignedString0(i, 2); 222 case 8 -> toOctalString(i); 223 case 10 -> { 224 /* 225 * We can get the effect of an unsigned division by 10 226 * on a long value by first shifting right, yielding a 227 * positive value, and then dividing by 5. This 228 * allows the last digit and preceding digits to be 229 * isolated more quickly than by an initial conversion 230 * to BigInteger. 231 */ 232 long quot = (i >>> 1) / 5; 233 long rem = i - quot * 10; 234 yield toString(quot) + rem; 235 } 236 case 16 -> toHexString(i); 237 case 32 -> toUnsignedString0(i, 5); 238 default -> toUnsignedBigInteger(i).toString(radix); 239 }; 240 } 241 } 242 243 /** 244 * Return a BigInteger equal to the unsigned value of the 245 * argument. 246 */ 247 private static BigInteger toUnsignedBigInteger(long i) { 248 if (i >= 0L) 249 return BigInteger.valueOf(i); 250 else { 251 int upper = (int) (i >>> 32); 252 int lower = (int) i; 253 254 // return (upper << 32) + lower 255 return (BigInteger.valueOf(Integer.toUnsignedLong(upper))).shiftLeft(32). 256 add(BigInteger.valueOf(Integer.toUnsignedLong(lower))); 257 } 258 } 259 260 /** 261 * Returns a string representation of the {@code long} 262 * argument as an unsigned integer in base 16. 263 * 264 * <p>The unsigned {@code long} value is the argument plus 265 * 2<sup>64</sup> if the argument is negative; otherwise, it is 266 * equal to the argument. This value is converted to a string of 267 * ASCII digits in hexadecimal (base 16) with no extra 268 * leading {@code 0}s. 269 * 270 * <p>The value of the argument can be recovered from the returned 271 * string {@code s} by calling {@link 272 * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s, 273 * 16)}. 274 * 275 * <p>If the unsigned magnitude is zero, it is represented by a 276 * single zero character {@code '0'} ({@code '\u005Cu0030'}); 277 * otherwise, the first character of the representation of the 278 * unsigned magnitude will not be the zero character. The 279 * following characters are used as hexadecimal digits: 280 * 281 * <blockquote> 282 * {@code 0123456789abcdef} 283 * </blockquote> 284 * 285 * These are the characters {@code '\u005Cu0030'} through 286 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through 287 * {@code '\u005Cu0066'}. If uppercase letters are desired, 288 * the {@link java.lang.String#toUpperCase()} method may be called 289 * on the result: 290 * 291 * <blockquote> 292 * {@code Long.toHexString(n).toUpperCase()} 293 * </blockquote> 294 * 295 * @apiNote 296 * The {@link java.util.HexFormat} class provides formatting and parsing 297 * of byte arrays and primitives to return a string or adding to an {@link Appendable}. 298 * {@code HexFormat} formats and parses uppercase or lowercase hexadecimal characters, 299 * with leading zeros and for byte arrays includes for each byte 300 * a delimiter, prefix, and suffix. 301 * 302 * @param i a {@code long} to be converted to a string. 303 * @return the string representation of the unsigned {@code long} 304 * value represented by the argument in hexadecimal 305 * (base 16). 306 * @see java.util.HexFormat 307 * @see #parseUnsignedLong(String, int) 308 * @see #toUnsignedString(long, int) 309 * @since 1.0.2 310 */ 311 public static String toHexString(long i) { 312 return toUnsignedString0(i, 4); 313 } 314 315 /** 316 * Returns a string representation of the {@code long} 317 * argument as an unsigned integer in base 8. 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 octal (base 8) 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 * 8)}. 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 * following characters are used as octal digits: 335 * 336 * <blockquote> 337 * {@code 01234567} 338 * </blockquote> 339 * 340 * These are the characters {@code '\u005Cu0030'} through 341 * {@code '\u005Cu0037'}. 342 * 343 * @param i a {@code long} to be converted to a string. 344 * @return the string representation of the unsigned {@code long} 345 * value represented by the argument in octal (base 8). 346 * @see #parseUnsignedLong(String, int) 347 * @see #toUnsignedString(long, int) 348 * @since 1.0.2 349 */ 350 public static String toOctalString(long i) { 351 return toUnsignedString0(i, 3); 352 } 353 354 /** 355 * Returns a string representation of the {@code long} 356 * argument as an unsigned integer in base 2. 357 * 358 * <p>The unsigned {@code long} value is the argument plus 359 * 2<sup>64</sup> if the argument is negative; otherwise, it is 360 * equal to the argument. This value is converted to a string of 361 * ASCII digits in binary (base 2) with no extra leading 362 * {@code 0}s. 363 * 364 * <p>The value of the argument can be recovered from the returned 365 * string {@code s} by calling {@link 366 * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s, 367 * 2)}. 368 * 369 * <p>If the unsigned magnitude is zero, it is represented by a 370 * single zero character {@code '0'} ({@code '\u005Cu0030'}); 371 * otherwise, the first character of the representation of the 372 * unsigned magnitude will not be the zero character. The 373 * characters {@code '0'} ({@code '\u005Cu0030'}) and {@code 374 * '1'} ({@code '\u005Cu0031'}) are used as binary digits. 375 * 376 * @param i a {@code long} to be converted to a string. 377 * @return the string representation of the unsigned {@code long} 378 * value represented by the argument in binary (base 2). 379 * @see #parseUnsignedLong(String, int) 380 * @see #toUnsignedString(long, int) 381 * @since 1.0.2 382 */ 383 public static String toBinaryString(long i) { 384 return toUnsignedString0(i, 1); 385 } 386 387 /** 388 * Format a long (treated as unsigned) into a String. 389 * @param val the value to format 390 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary) 391 */ 392 static String toUnsignedString0(long val, int shift) { 393 // assert shift > 0 && shift <=5 : "Illegal shift value"; 394 int mag = Long.SIZE - Long.numberOfLeadingZeros(val); 395 int chars = Math.max(((mag + (shift - 1)) / shift), 1); 396 if (COMPACT_STRINGS) { 397 byte[] buf = new byte[chars]; 398 formatUnsignedLong0(val, shift, buf, 0, chars); 399 return new String(buf, LATIN1); 400 } else { 401 byte[] buf = new byte[chars * 2]; 402 formatUnsignedLong0UTF16(val, shift, buf, 0, chars); 403 return new String(buf, UTF16); 404 } 405 } 406 407 /** 408 * Format a long (treated as unsigned) into a byte buffer (LATIN1 version). If 409 * {@code len} exceeds the formatted ASCII representation of {@code val}, 410 * {@code buf} will be padded with leading zeroes. 411 * 412 * @param val the unsigned long to format 413 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary) 414 * @param buf the byte buffer to write to 415 * @param offset the offset in the destination buffer to start at 416 * @param len the number of characters to write 417 */ 418 private static void formatUnsignedLong0(long val, int shift, byte[] buf, int offset, int len) { 419 int charPos = offset + len; 420 int radix = 1 << shift; 421 int mask = radix - 1; 422 do { 423 buf[--charPos] = (byte)Integer.digits[((int) val) & mask]; 424 val >>>= shift; 425 } while (charPos > offset); 426 } 427 428 /** 429 * Format a long (treated as unsigned) into a byte buffer (UTF16 version). If 430 * {@code len} exceeds the formatted ASCII representation of {@code val}, 431 * {@code buf} will be padded with leading zeroes. 432 * 433 * @param val the unsigned long to format 434 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary) 435 * @param buf the byte buffer to write to 436 * @param offset the offset in the destination buffer to start at 437 * @param len the number of characters to write 438 */ 439 private static void formatUnsignedLong0UTF16(long val, int shift, byte[] buf, int offset, int len) { 440 int charPos = offset + len; 441 int radix = 1 << shift; 442 int mask = radix - 1; 443 do { 444 StringUTF16.putChar(buf, --charPos, Integer.digits[((int) val) & mask]); 445 val >>>= shift; 446 } while (charPos > offset); 447 } 448 449 /** 450 * Returns a {@code String} object representing the specified 451 * {@code long}. The argument is converted to signed decimal 452 * representation and returned as a string, exactly as if the 453 * argument and the radix 10 were given as arguments to the {@link 454 * #toString(long, int)} method. 455 * 456 * @param i a {@code long} to be converted. 457 * @return a string representation of the argument in base 10. 458 */ 459 public static String toString(long i) { 460 int size = stringSize(i); 461 if (COMPACT_STRINGS) { 462 byte[] buf = new byte[size]; 463 StringLatin1.getChars(i, size, buf); 464 return new String(buf, LATIN1); 465 } else { 466 byte[] buf = new byte[size * 2]; 467 StringUTF16.getChars(i, size, buf); 468 return new String(buf, UTF16); 469 } 470 } 471 472 /** 473 * Returns a string representation of the argument as an unsigned 474 * decimal value. 475 * 476 * The argument is converted to unsigned decimal representation 477 * and returned as a string exactly as if the argument and radix 478 * 10 were given as arguments to the {@link #toUnsignedString(long, 479 * int)} method. 480 * 481 * @param i an integer to be converted to an unsigned string. 482 * @return an unsigned string representation of the argument. 483 * @see #toUnsignedString(long, int) 484 * @since 1.8 485 */ 486 public static String toUnsignedString(long i) { 487 return toUnsignedString(i, 10); 488 } 489 490 /** 491 * Returns the string representation size for a given long value. 492 * 493 * @param x long value 494 * @return string size 495 * 496 * @implNote There are other ways to compute this: e.g. binary search, 497 * but values are biased heavily towards zero, and therefore linear search 498 * wins. The iteration results are also routinely inlined in the generated 499 * code after loop unrolling. 500 */ 501 static int stringSize(long x) { 502 int d = 1; 503 if (x >= 0) { 504 d = 0; 505 x = -x; 506 } 507 long p = -10; 508 for (int i = 1; i < 19; i++) { 509 if (x > p) 510 return i + d; 511 p = 10 * p; 512 } 513 return 19 + d; 514 } 515 516 /** 517 * Parses the string argument as a signed {@code long} in the 518 * radix specified by the second argument. The characters in the 519 * string must all be digits of the specified radix (as determined 520 * by whether {@link java.lang.Character#digit(char, int)} returns 521 * a nonnegative value), except that the first character may be an 522 * ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to 523 * indicate a negative value or an ASCII plus sign {@code '+'} 524 * ({@code '\u005Cu002B'}) to indicate a positive value. The 525 * resulting {@code long} value is returned. 526 * 527 * <p>Note that neither the character {@code L} 528 * ({@code '\u005Cu004C'}) nor {@code l} 529 * ({@code '\u005Cu006C'}) is permitted to appear at the end 530 * of the string as a type indicator, as would be permitted in 531 * Java programming language source code - except that either 532 * {@code L} or {@code l} may appear as a digit for a 533 * radix greater than or equal to 22. 534 * 535 * <p>An exception of type {@code NumberFormatException} is 536 * thrown if any of the following situations occurs: 537 * <ul> 538 * 539 * <li>The first argument is {@code null} or is a string of 540 * length zero. 541 * 542 * <li>The {@code radix} is either smaller than {@link 543 * java.lang.Character#MIN_RADIX} or larger than {@link 544 * java.lang.Character#MAX_RADIX}. 545 * 546 * <li>Any character of the string is not a digit of the specified 547 * radix, except that the first character may be a minus sign 548 * {@code '-'} ({@code '\u005Cu002d'}) or plus sign {@code 549 * '+'} ({@code '\u005Cu002B'}) provided that the string is 550 * longer than length 1. 551 * 552 * <li>The value represented by the string is not a value of type 553 * {@code long}. 554 * </ul> 555 * 556 * <p>Examples: 557 * <blockquote><pre> 558 * parseLong("0", 10) returns 0L 559 * parseLong("473", 10) returns 473L 560 * parseLong("+42", 10) returns 42L 561 * parseLong("-0", 10) returns 0L 562 * parseLong("-FF", 16) returns -255L 563 * parseLong("1100110", 2) returns 102L 564 * parseLong("99", 8) throws a NumberFormatException 565 * parseLong("Hazelnut", 10) throws a NumberFormatException 566 * parseLong("Hazelnut", 36) returns 1356099454469L 567 * </pre></blockquote> 568 * 569 * @param s the {@code String} containing the 570 * {@code long} representation to be parsed. 571 * @param radix the radix to be used while parsing {@code s}. 572 * @return the {@code long} represented by the string argument in 573 * the specified radix. 574 * @throws NumberFormatException if the string does not contain a 575 * parsable {@code long}. 576 */ 577 public static long parseLong(String s, int radix) 578 throws NumberFormatException { 579 if (s == null) { 580 throw new NumberFormatException("Cannot parse null string"); 581 } 582 583 if (radix < Character.MIN_RADIX) { 584 throw new NumberFormatException(String.format( 585 "radix %s less than Character.MIN_RADIX", radix)); 586 } 587 588 if (radix > Character.MAX_RADIX) { 589 throw new NumberFormatException(String.format( 590 "radix %s greater than Character.MAX_RADIX", radix)); 591 } 592 593 int len = s.length(); 594 if (len == 0) { 595 throw NumberFormatException.forInputString("", radix); 596 } 597 int digit = ~0xFF; 598 int i = 0; 599 char firstChar = s.charAt(i++); 600 if (firstChar != '-' && firstChar != '+') { 601 digit = digit(firstChar, radix); 602 } 603 if (digit >= 0 || digit == ~0xFF && len > 1) { 604 long limit = firstChar != '-' ? MIN_VALUE + 1 : MIN_VALUE; 605 long multmin = limit / radix; 606 long result = -(digit & 0xFF); 607 boolean inRange = true; 608 /* Accumulating negatively avoids surprises near MAX_VALUE */ 609 while (i < len && (digit = digit(s.charAt(i++), radix)) >= 0 610 && (inRange = result > multmin 611 || result == multmin && digit <= (int) (radix * multmin - limit))) { 612 result = radix * result - digit; 613 } 614 if (inRange && i == len && digit >= 0) { 615 return firstChar != '-' ? -result : result; 616 } 617 } 618 throw NumberFormatException.forInputString(s, radix); 619 } 620 621 /** 622 * Parses the {@link CharSequence} argument as a signed {@code long} in 623 * the specified {@code radix}, beginning at the specified 624 * {@code beginIndex} and extending to {@code endIndex - 1}. 625 * 626 * <p>The method does not take steps to guard against the 627 * {@code CharSequence} being mutated while parsing. 628 * 629 * @param s the {@code CharSequence} containing the {@code long} 630 * representation to be parsed 631 * @param beginIndex the beginning index, inclusive. 632 * @param endIndex the ending index, exclusive. 633 * @param radix the radix to be used while parsing {@code s}. 634 * @return the signed {@code long} represented by the subsequence in 635 * the specified radix. 636 * @throws NullPointerException if {@code s} is null. 637 * @throws IndexOutOfBoundsException if {@code beginIndex} is 638 * negative, or if {@code beginIndex} is greater than 639 * {@code endIndex} or if {@code endIndex} is greater than 640 * {@code s.length()}. 641 * @throws NumberFormatException if the {@code CharSequence} does not 642 * contain a parsable {@code long} in the specified 643 * {@code radix}, or if {@code radix} is either smaller than 644 * {@link java.lang.Character#MIN_RADIX} or larger than 645 * {@link java.lang.Character#MAX_RADIX}. 646 * @since 9 647 */ 648 public static long parseLong(CharSequence s, int beginIndex, int endIndex, int radix) 649 throws NumberFormatException { 650 Objects.requireNonNull(s); 651 Objects.checkFromToIndex(beginIndex, endIndex, s.length()); 652 653 if (radix < Character.MIN_RADIX) { 654 throw new NumberFormatException(String.format( 655 "radix %s less than Character.MIN_RADIX", radix)); 656 } 657 658 if (radix > Character.MAX_RADIX) { 659 throw new NumberFormatException(String.format( 660 "radix %s greater than Character.MAX_RADIX", radix)); 661 } 662 663 /* 664 * While s can be concurrently modified, it is ensured that each 665 * of its characters is read at most once, from lower to higher indices. 666 * This is obtained by reading them using the pattern s.charAt(i++), 667 * and by not updating i anywhere else. 668 */ 669 if (beginIndex == endIndex) { 670 throw NumberFormatException.forInputString("", radix); 671 } 672 int digit = ~0xFF; // ~0xFF means firstChar char is sign 673 int i = beginIndex; 674 char firstChar = s.charAt(i++); 675 if (firstChar != '-' && firstChar != '+') { 676 digit = digit(firstChar, radix); 677 } 678 if (digit >= 0 || digit == ~0xFF && endIndex - beginIndex > 1) { 679 long limit = firstChar != '-' ? MIN_VALUE + 1 : MIN_VALUE; 680 long multmin = limit / radix; 681 long result = -(digit & 0xFF); 682 boolean inRange = true; 683 /* Accumulating negatively avoids surprises near MAX_VALUE */ 684 while (i < endIndex && (digit = digit(s.charAt(i++), radix)) >= 0 685 && (inRange = result > multmin 686 || result == multmin && digit <= (int) (radix * multmin - limit))) { 687 result = radix * result - digit; 688 } 689 if (inRange && i == endIndex && digit >= 0) { 690 return firstChar != '-' ? -result : result; 691 } 692 } 693 throw NumberFormatException.forCharSequence(s, beginIndex, 694 endIndex, i - (digit < -1 ? 0 : 1)); 695 } 696 697 /** 698 * Parses the string argument as a signed decimal {@code long}. 699 * The characters in the string must all be decimal digits, except 700 * that the first character may be an ASCII minus sign {@code '-'} 701 * ({@code \u005Cu002D'}) to indicate a negative value or an 702 * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to 703 * indicate a positive value. The resulting {@code long} value is 704 * returned, exactly as if the argument and the radix {@code 10} 705 * were given as arguments to the {@link 706 * #parseLong(java.lang.String, int)} method. 707 * 708 * <p>Note that neither the character {@code L} 709 * ({@code '\u005Cu004C'}) nor {@code l} 710 * ({@code '\u005Cu006C'}) is permitted to appear at the end 711 * of the string as a type indicator, as would be permitted in 712 * Java programming language source code. 713 * 714 * @param s a {@code String} containing the {@code long} 715 * representation to be parsed 716 * @return the {@code long} represented by the argument in 717 * decimal. 718 * @throws NumberFormatException if the string does not contain a 719 * parsable {@code long}. 720 */ 721 public static long parseLong(String s) throws NumberFormatException { 722 return parseLong(s, 10); 723 } 724 725 /** 726 * Parses the string argument as an unsigned {@code long} in the 727 * radix specified by the second argument. An unsigned integer 728 * maps the values usually associated with negative numbers to 729 * positive numbers larger than {@code MAX_VALUE}. 730 * 731 * The characters in the string must all be digits of the 732 * specified radix (as determined by whether {@link 733 * java.lang.Character#digit(char, int)} returns a nonnegative 734 * value), except that the first character may be an ASCII plus 735 * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting 736 * integer value is returned. 737 * 738 * <p>An exception of type {@code NumberFormatException} is 739 * thrown if any of the following situations occurs: 740 * <ul> 741 * <li>The first argument is {@code null} or is a string of 742 * length zero. 743 * 744 * <li>The radix is either smaller than 745 * {@link java.lang.Character#MIN_RADIX} or 746 * larger than {@link java.lang.Character#MAX_RADIX}. 747 * 748 * <li>Any character of the string is not a digit of the specified 749 * radix, except that the first character may be a plus sign 750 * {@code '+'} ({@code '\u005Cu002B'}) provided that the 751 * string is longer than length 1. 752 * 753 * <li>The value represented by the string is larger than the 754 * largest unsigned {@code long}, 2<sup>64</sup>-1. 755 * 756 * </ul> 757 * 758 * 759 * @param s the {@code String} containing the unsigned integer 760 * representation to be parsed 761 * @param radix the radix to be used while parsing {@code s}. 762 * @return the unsigned {@code long} represented by the string 763 * argument in the specified radix. 764 * @throws NumberFormatException if the {@code String} 765 * does not contain a parsable {@code long}. 766 * @since 1.8 767 */ 768 public static long parseUnsignedLong(String s, int radix) 769 throws NumberFormatException { 770 if (s == null) { 771 throw new NumberFormatException("Cannot parse null string"); 772 } 773 774 if (radix < Character.MIN_RADIX) { 775 throw new NumberFormatException(String.format( 776 "radix %s less than Character.MIN_RADIX", radix)); 777 } 778 779 if (radix > Character.MAX_RADIX) { 780 throw new NumberFormatException(String.format( 781 "radix %s greater than Character.MAX_RADIX", radix)); 782 } 783 784 int len = s.length(); 785 if (len == 0) { 786 throw NumberFormatException.forInputString(s, radix); 787 } 788 int i = 0; 789 char firstChar = s.charAt(i++); 790 if (firstChar == '-') { 791 throw new NumberFormatException(String.format( 792 "Illegal leading minus sign on unsigned string %s.", s)); 793 } 794 int digit = ~0xFF; 795 if (firstChar != '+') { 796 digit = digit(firstChar, radix); 797 } 798 if (digit >= 0 || digit == ~0xFF && len > 1) { 799 long multmax = divideUnsigned(-1L, radix); // -1L is max unsigned long 800 long result = digit & 0xFF; 801 boolean inRange = true; 802 while (i < len && (digit = digit(s.charAt(i++), radix)) >= 0 803 && (inRange = compareUnsigned(result, multmax) < 0 804 || result == multmax && digit < (int) (-radix * multmax))) { 805 result = radix * result + digit; 806 } 807 if (inRange && i == len && digit >= 0) { 808 return result; 809 } 810 } 811 if (digit < 0) { 812 throw NumberFormatException.forInputString(s, radix); 813 } 814 throw new NumberFormatException(String.format( 815 "String value %s exceeds range of unsigned long.", s)); 816 } 817 818 /** 819 * Parses the {@link CharSequence} argument as an unsigned {@code long} in 820 * the specified {@code radix}, beginning at the specified 821 * {@code beginIndex} and extending to {@code endIndex - 1}. 822 * 823 * <p>The method does not take steps to guard against the 824 * {@code CharSequence} being mutated while parsing. 825 * 826 * @param s the {@code CharSequence} containing the unsigned 827 * {@code long} representation to be parsed 828 * @param beginIndex the beginning index, inclusive. 829 * @param endIndex the ending index, exclusive. 830 * @param radix the radix to be used while parsing {@code s}. 831 * @return the unsigned {@code long} represented by the subsequence in 832 * the specified radix. 833 * @throws NullPointerException if {@code s} is null. 834 * @throws IndexOutOfBoundsException if {@code beginIndex} is 835 * negative, or if {@code beginIndex} is greater than 836 * {@code endIndex} or if {@code endIndex} is greater than 837 * {@code s.length()}. 838 * @throws NumberFormatException if the {@code CharSequence} does not 839 * contain a parsable unsigned {@code long} in the specified 840 * {@code radix}, or if {@code radix} is either smaller than 841 * {@link java.lang.Character#MIN_RADIX} or larger than 842 * {@link java.lang.Character#MAX_RADIX}. 843 * @since 9 844 */ 845 public static long parseUnsignedLong(CharSequence s, int beginIndex, int endIndex, int radix) 846 throws NumberFormatException { 847 Objects.requireNonNull(s); 848 Objects.checkFromToIndex(beginIndex, endIndex, s.length()); 849 850 if (radix < Character.MIN_RADIX) { 851 throw new NumberFormatException(String.format( 852 "radix %s less than Character.MIN_RADIX", radix)); 853 } 854 855 if (radix > Character.MAX_RADIX) { 856 throw new NumberFormatException(String.format( 857 "radix %s greater than Character.MAX_RADIX", radix)); 858 } 859 860 /* 861 * While s can be concurrently modified, it is ensured that each 862 * of its characters is read at most once, from lower to higher indices. 863 * This is obtained by reading them using the pattern s.charAt(i++), 864 * and by not updating i anywhere else. 865 */ 866 if (beginIndex == endIndex) { 867 throw NumberFormatException.forInputString("", radix); 868 } 869 int i = beginIndex; 870 char firstChar = s.charAt(i++); 871 if (firstChar == '-') { 872 throw new NumberFormatException( 873 "Illegal leading minus sign on unsigned string " + s + "."); 874 } 875 int digit = ~0xFF; 876 if (firstChar != '+') { 877 digit = digit(firstChar, radix); 878 } 879 if (digit >= 0 || digit == ~0xFF && endIndex - beginIndex > 1) { 880 long multmax = divideUnsigned(-1L, radix); // -1L is max unsigned long 881 long result = digit & 0xFF; 882 boolean inRange = true; 883 while (i < endIndex && (digit = digit(s.charAt(i++), radix)) >= 0 884 && (inRange = compareUnsigned(result, multmax) < 0 885 || result == multmax && digit < (int) (-radix * multmax))) { 886 result = radix * result + digit; 887 } 888 if (inRange && i == endIndex && digit >= 0) { 889 return result; 890 } 891 } 892 if (digit < 0) { 893 throw NumberFormatException.forCharSequence(s, beginIndex, 894 endIndex, i - (digit < -1 ? 0 : 1)); 895 } 896 throw new NumberFormatException(String.format( 897 "String value %s exceeds range of unsigned long.", s)); 898 } 899 900 /** 901 * Parses the string argument as an unsigned decimal {@code long}. The 902 * characters in the string must all be decimal digits, except 903 * that the first character may be an ASCII plus sign {@code 904 * '+'} ({@code '\u005Cu002B'}). The resulting integer value 905 * is returned, exactly as if the argument and the radix 10 were 906 * given as arguments to the {@link 907 * #parseUnsignedLong(java.lang.String, int)} method. 908 * 909 * @param s a {@code String} containing the unsigned {@code long} 910 * representation to be parsed 911 * @return the unsigned {@code long} value represented by the decimal string argument 912 * @throws NumberFormatException if the string does not contain a 913 * parsable unsigned integer. 914 * @since 1.8 915 */ 916 public static long parseUnsignedLong(String s) throws NumberFormatException { 917 return parseUnsignedLong(s, 10); 918 } 919 920 /** 921 * Returns a {@code Long} object holding the value 922 * extracted from the specified {@code String} when parsed 923 * with the radix given by the second argument. The first 924 * argument is interpreted as representing a signed 925 * {@code long} in the radix specified by the second 926 * argument, exactly as if the arguments were given to the {@link 927 * #parseLong(java.lang.String, int)} method. The result is a 928 * {@code Long} object that represents the {@code long} 929 * value specified by the string. 930 * 931 * <p>In other words, this method returns a {@code Long} object equal 932 * to the value of: 933 * 934 * <blockquote> 935 * {@code Long.valueOf(Long.parseLong(s, radix))} 936 * </blockquote> 937 * 938 * @param s the string to be parsed 939 * @param radix the radix to be used in interpreting {@code s} 940 * @return a {@code Long} object holding the value 941 * represented by the string argument in the specified 942 * radix. 943 * @throws NumberFormatException If the {@code String} does not 944 * contain a parsable {@code long}. 945 */ 946 public static Long valueOf(String s, int radix) throws NumberFormatException { 947 return Long.valueOf(parseLong(s, radix)); 948 } 949 950 /** 951 * Returns a {@code Long} object holding the value 952 * of the specified {@code String}. The argument is 953 * interpreted as representing a signed decimal {@code long}, 954 * exactly as if the argument were given to the {@link 955 * #parseLong(java.lang.String)} method. The result is a 956 * {@code Long} object that represents the integer value 957 * specified by the string. 958 * 959 * <p>In other words, this method returns a {@code Long} object 960 * equal to the value of: 961 * 962 * <blockquote> 963 * {@code Long.valueOf(Long.parseLong(s))} 964 * </blockquote> 965 * 966 * @param s the string to be parsed. 967 * @return a {@code Long} object holding the value 968 * represented by the string argument. 969 * @throws NumberFormatException If the string cannot be parsed 970 * as a {@code long}. 971 */ 972 public static Long valueOf(String s) throws NumberFormatException 973 { 974 return Long.valueOf(parseLong(s, 10)); 975 } 976 977 private static final class LongCache { 978 private LongCache() {} 979 980 @Stable 981 static final Long[] cache; 982 static Long[] archivedCache; 983 984 static { 985 int size = -(-128) + 127 + 1; 986 987 // Load and use the archived cache if it exists 988 CDS.initializeFromArchive(LongCache.class); 989 if (archivedCache == null || archivedCache.length != size) { 990 Long[] c = new Long[size]; 991 long value = -128; 992 for(int i = 0; i < size; i++) { 993 c[i] = new Long(value++); 994 } 995 archivedCache = c; 996 } 997 cache = archivedCache; 998 } 999 } 1000 1001 /** 1002 * Returns a {@code Long} instance representing the specified 1003 * {@code long} value. 1004 * If a new {@code Long} instance is not required, this method 1005 * should generally be used in preference to the constructor 1006 * {@link #Long(long)}, as this method is likely to yield 1007 * significantly better space and time performance by caching 1008 * frequently requested values. 1009 * 1010 * This method will always cache values in the range -128 to 127, 1011 * inclusive, and may cache other values outside of this range. 1012 * 1013 * @param l a long value. 1014 * @return a {@code Long} instance representing {@code l}. 1015 * @since 1.5 1016 */ 1017 @IntrinsicCandidate 1018 public static Long valueOf(long l) { 1019 final int offset = 128; 1020 if (l >= -128 && l <= 127) { // will cache 1021 return LongCache.cache[(int)l + offset]; 1022 } 1023 return new Long(l); 1024 } 1025 1026 /** 1027 * Decodes a {@code String} into a {@code Long}. 1028 * Accepts decimal, hexadecimal, and octal numbers given by the 1029 * following grammar: 1030 * 1031 * <blockquote> 1032 * <dl> 1033 * <dt><i>DecodableString:</i> 1034 * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i> 1035 * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i> 1036 * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i> 1037 * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i> 1038 * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i> 1039 * 1040 * <dt><i>Sign:</i> 1041 * <dd>{@code -} 1042 * <dd>{@code +} 1043 * </dl> 1044 * </blockquote> 1045 * 1046 * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i> 1047 * are as defined in section {@jls 3.10.1} of 1048 * <cite>The Java Language Specification</cite>, 1049 * except that underscores are not accepted between digits. 1050 * 1051 * <p>The sequence of characters following an optional 1052 * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", 1053 * "{@code #}", or leading zero) is parsed as by the {@code 1054 * Long.parseLong} method with the indicated radix (10, 16, or 8). 1055 * This sequence of characters must represent a positive value or 1056 * a {@link NumberFormatException} will be thrown. The result is 1057 * negated if first character of the specified {@code String} is 1058 * the minus sign. No whitespace characters are permitted in the 1059 * {@code String}. 1060 * 1061 * @param nm the {@code String} to decode. 1062 * @return a {@code Long} object holding the {@code long} 1063 * value represented by {@code nm} 1064 * @throws NumberFormatException if the {@code String} does not 1065 * contain a parsable {@code long}. 1066 * @see java.lang.Long#parseLong(String, int) 1067 * @since 1.2 1068 */ 1069 public static Long decode(String nm) throws NumberFormatException { 1070 int radix = 10; 1071 int index = 0; 1072 boolean negative = false; 1073 long result; 1074 1075 if (nm.isEmpty()) 1076 throw new NumberFormatException("Zero length string"); 1077 char firstChar = nm.charAt(0); 1078 // Handle sign, if present 1079 if (firstChar == '-') { 1080 negative = true; 1081 index++; 1082 } else if (firstChar == '+') 1083 index++; 1084 1085 // Handle radix specifier, if present 1086 if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) { 1087 index += 2; 1088 radix = 16; 1089 } 1090 else if (nm.startsWith("#", index)) { 1091 index ++; 1092 radix = 16; 1093 } 1094 else if (nm.startsWith("0", index) && nm.length() > 1 + index) { 1095 index ++; 1096 radix = 8; 1097 } 1098 1099 if (nm.startsWith("-", index) || nm.startsWith("+", index)) 1100 throw new NumberFormatException("Sign character in wrong position"); 1101 1102 try { 1103 result = parseLong(nm, index, nm.length(), radix); 1104 result = negative ? -result : result; 1105 } catch (NumberFormatException e) { 1106 // If number is Long.MIN_VALUE, we'll end up here. The next line 1107 // handles this case, and causes any genuine format error to be 1108 // rethrown. 1109 String constant = negative ? ("-" + nm.substring(index)) 1110 : nm.substring(index); 1111 result = parseLong(constant, radix); 1112 } 1113 return result; 1114 } 1115 1116 /** 1117 * The value of the {@code Long}. 1118 * 1119 * @serial 1120 */ 1121 private final long value; 1122 1123 /** 1124 * Constructs a newly allocated {@code Long} object that 1125 * represents the specified {@code long} argument. 1126 * 1127 * @param value the value to be represented by the 1128 * {@code Long} object. 1129 * 1130 * @deprecated 1131 * It is rarely appropriate to use this constructor. The static factory 1132 * {@link #valueOf(long)} is generally a better choice, as it is 1133 * likely to yield significantly better space and time performance. 1134 */ 1135 @Deprecated(since="9", forRemoval = true) 1136 public Long(long value) { 1137 this.value = value; 1138 } 1139 1140 /** 1141 * Constructs a newly allocated {@code Long} object that 1142 * represents the {@code long} value indicated by the 1143 * {@code String} parameter. The string is converted to a 1144 * {@code long} value in exactly the manner used by the 1145 * {@code parseLong} method for radix 10. 1146 * 1147 * @param s the {@code String} to be converted to a 1148 * {@code Long}. 1149 * @throws NumberFormatException if the {@code String} does not 1150 * contain a parsable {@code long}. 1151 * 1152 * @deprecated 1153 * It is rarely appropriate to use this constructor. 1154 * Use {@link #parseLong(String)} to convert a string to a 1155 * {@code long} primitive, or use {@link #valueOf(String)} 1156 * to convert a string to a {@code Long} object. 1157 */ 1158 @Deprecated(since="9", forRemoval = true) 1159 public Long(String s) throws NumberFormatException { 1160 this.value = parseLong(s, 10); 1161 } 1162 1163 /** 1164 * Returns the value of this {@code Long} as a {@code byte} after 1165 * a narrowing primitive conversion. 1166 * @jls 5.1.3 Narrowing Primitive Conversion 1167 */ 1168 public byte byteValue() { 1169 return (byte)value; 1170 } 1171 1172 /** 1173 * Returns the value of this {@code Long} as a {@code short} after 1174 * a narrowing primitive conversion. 1175 * @jls 5.1.3 Narrowing Primitive Conversion 1176 */ 1177 public short shortValue() { 1178 return (short)value; 1179 } 1180 1181 /** 1182 * Returns the value of this {@code Long} as an {@code int} after 1183 * a narrowing primitive conversion. 1184 * @jls 5.1.3 Narrowing Primitive Conversion 1185 */ 1186 public int intValue() { 1187 return (int)value; 1188 } 1189 1190 /** 1191 * Returns the value of this {@code Long} as a 1192 * {@code long} value. 1193 */ 1194 @IntrinsicCandidate 1195 public long longValue() { 1196 return value; 1197 } 1198 1199 /** 1200 * Returns the value of this {@code Long} as a {@code float} after 1201 * a widening primitive conversion. 1202 * @jls 5.1.2 Widening Primitive Conversion 1203 */ 1204 public float floatValue() { 1205 return (float)value; 1206 } 1207 1208 /** 1209 * Returns the value of this {@code Long} as a {@code double} 1210 * after a widening primitive conversion. 1211 * @jls 5.1.2 Widening Primitive Conversion 1212 */ 1213 public double doubleValue() { 1214 return (double)value; 1215 } 1216 1217 /** 1218 * Returns a {@code String} object representing this 1219 * {@code Long}'s value. The value is converted to signed 1220 * decimal representation and returned as a string, exactly as if 1221 * the {@code long} value were given as an argument to the 1222 * {@link java.lang.Long#toString(long)} method. 1223 * 1224 * @return a string representation of the value of this object in 1225 * base 10. 1226 */ 1227 public String toString() { 1228 return toString(value); 1229 } 1230 1231 /** 1232 * Returns a hash code for this {@code Long}. The result is 1233 * the exclusive OR of the two halves of the primitive 1234 * {@code long} value held by this {@code Long} 1235 * object. That is, the hashcode is the value of the expression: 1236 * 1237 * <blockquote> 1238 * {@code (int)(this.longValue()^(this.longValue()>>>32))} 1239 * </blockquote> 1240 * 1241 * @return a hash code value for this object. 1242 */ 1243 @Override 1244 public int hashCode() { 1245 return Long.hashCode(value); 1246 } 1247 1248 /** 1249 * Returns a hash code for a {@code long} value; compatible with 1250 * {@code Long.hashCode()}. 1251 * 1252 * @param value the value to hash 1253 * @return a hash code value for a {@code long} value. 1254 * @since 1.8 1255 */ 1256 public static int hashCode(long value) { 1257 return (int)(value ^ (value >>> 32)); 1258 } 1259 1260 /** 1261 * Compares this object to the specified object. The result is 1262 * {@code true} if and only if the argument is not 1263 * {@code null} and is a {@code Long} object that 1264 * contains the same {@code long} value as this object. 1265 * 1266 * @param obj the object to compare with. 1267 * @return {@code true} if the objects are the same; 1268 * {@code false} otherwise. 1269 */ 1270 public boolean equals(Object obj) { 1271 if (obj instanceof Long) { 1272 return value == ((Long)obj).longValue(); 1273 } 1274 return false; 1275 } 1276 1277 /** 1278 * Determines the {@code long} value of the system property 1279 * with the specified name. 1280 * 1281 * <p>The first argument is treated as the name of a system 1282 * property. System properties are accessible through the {@link 1283 * java.lang.System#getProperty(java.lang.String)} method. The 1284 * string value of this property is then interpreted as a {@code 1285 * long} value using the grammar supported by {@link Long#decode decode} 1286 * and a {@code Long} object representing this value is returned. 1287 * 1288 * <p>If there is no property with the specified name, if the 1289 * specified name is empty or {@code null}, or if the property 1290 * does not have the correct numeric format, then {@code null} is 1291 * returned. 1292 * 1293 * <p>In other words, this method returns a {@code Long} object 1294 * equal to the value of: 1295 * 1296 * <blockquote> 1297 * {@code getLong(nm, null)} 1298 * </blockquote> 1299 * 1300 * @param nm property name. 1301 * @return the {@code Long} value of the property. 1302 * @throws SecurityException for the same reasons as 1303 * {@link System#getProperty(String) System.getProperty} 1304 * @see java.lang.System#getProperty(java.lang.String) 1305 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1306 */ 1307 public static Long getLong(String nm) { 1308 return getLong(nm, null); 1309 } 1310 1311 /** 1312 * Determines the {@code long} value of the system property 1313 * with the specified name. 1314 * 1315 * <p>The first argument is treated as the name of a system 1316 * property. System properties are accessible through the {@link 1317 * java.lang.System#getProperty(java.lang.String)} method. The 1318 * string value of this property is then interpreted as a {@code 1319 * long} value using the grammar supported by {@link Long#decode decode} 1320 * and a {@code Long} object representing this value is returned. 1321 * 1322 * <p>The second argument is the default value. A {@code Long} object 1323 * that represents the value of the second argument is returned if there 1324 * is no property of the specified name, if the property does not have 1325 * the correct numeric format, or if the specified name is empty or null. 1326 * 1327 * <p>In other words, this method returns a {@code Long} object equal 1328 * to the value of: 1329 * 1330 * <blockquote> 1331 * {@code getLong(nm, Long.valueOf(val))} 1332 * </blockquote> 1333 * 1334 * but in practice it may be implemented in a manner such as: 1335 * 1336 * <blockquote><pre> 1337 * Long result = getLong(nm, null); 1338 * return (result == null) ? Long.valueOf(val) : result; 1339 * </pre></blockquote> 1340 * 1341 * to avoid the unnecessary allocation of a {@code Long} object when 1342 * the default value is not needed. 1343 * 1344 * @param nm property name. 1345 * @param val default value. 1346 * @return the {@code Long} value of the property. 1347 * @throws SecurityException for the same reasons as 1348 * {@link System#getProperty(String) System.getProperty} 1349 * @see java.lang.System#getProperty(java.lang.String) 1350 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1351 */ 1352 public static Long getLong(String nm, long val) { 1353 Long result = Long.getLong(nm, null); 1354 return (result == null) ? Long.valueOf(val) : result; 1355 } 1356 1357 /** 1358 * Returns the {@code long} value of the system property with 1359 * the specified name. The first argument is treated as the name 1360 * of a system property. System properties are accessible through 1361 * the {@link java.lang.System#getProperty(java.lang.String)} 1362 * method. The string value of this property is then interpreted 1363 * as a {@code long} value, as per the 1364 * {@link Long#decode decode} method, and a {@code Long} object 1365 * representing this value is returned; in summary: 1366 * 1367 * <ul> 1368 * <li>If the property value begins with the two ASCII characters 1369 * {@code 0x} or the ASCII character {@code #}, not followed by 1370 * a minus sign, then the rest of it is parsed as a hexadecimal integer 1371 * exactly as for the method {@link #valueOf(java.lang.String, int)} 1372 * with radix 16. 1373 * <li>If the property value begins with the ASCII character 1374 * {@code 0} followed by another character, it is parsed as 1375 * an octal integer exactly as by the method {@link 1376 * #valueOf(java.lang.String, int)} with radix 8. 1377 * <li>Otherwise the property value is parsed as a decimal 1378 * integer exactly as by the method 1379 * {@link #valueOf(java.lang.String, int)} with radix 10. 1380 * </ul> 1381 * 1382 * <p>Note that, in every case, neither {@code L} 1383 * ({@code '\u005Cu004C'}) nor {@code l} 1384 * ({@code '\u005Cu006C'}) is permitted to appear at the end 1385 * of the property value as a type indicator, as would be 1386 * permitted in Java programming language source code. 1387 * 1388 * <p>The second argument is the default value. The default value is 1389 * returned if there is no property of the specified name, if the 1390 * property does not have the correct numeric format, or if the 1391 * specified name is empty or {@code null}. 1392 * 1393 * @param nm property name. 1394 * @param val default value. 1395 * @return the {@code Long} value of the property. 1396 * @throws SecurityException for the same reasons as 1397 * {@link System#getProperty(String) System.getProperty} 1398 * @see System#getProperty(java.lang.String) 1399 * @see System#getProperty(java.lang.String, java.lang.String) 1400 */ 1401 public static Long getLong(String nm, Long val) { 1402 String v = null; 1403 try { 1404 v = System.getProperty(nm); 1405 } catch (IllegalArgumentException | NullPointerException e) { 1406 } 1407 if (v != null) { 1408 try { 1409 return Long.decode(v); 1410 } catch (NumberFormatException e) { 1411 } 1412 } 1413 return val; 1414 } 1415 1416 /** 1417 * Compares two {@code Long} objects numerically. 1418 * 1419 * @param anotherLong the {@code Long} to be compared. 1420 * @return the value {@code 0} if this {@code Long} is 1421 * equal to the argument {@code Long}; a value less than 1422 * {@code 0} if this {@code Long} is numerically less 1423 * than the argument {@code Long}; and a value greater 1424 * than {@code 0} if this {@code Long} is numerically 1425 * greater than the argument {@code Long} (signed 1426 * comparison). 1427 * @since 1.2 1428 */ 1429 public int compareTo(Long anotherLong) { 1430 return compare(this.value, anotherLong.value); 1431 } 1432 1433 /** 1434 * Compares two {@code long} values numerically. 1435 * The value returned is identical to what would be returned by: 1436 * <pre> 1437 * Long.valueOf(x).compareTo(Long.valueOf(y)) 1438 * </pre> 1439 * 1440 * @param x the first {@code long} to compare 1441 * @param y the second {@code long} to compare 1442 * @return the value {@code 0} if {@code x == y}; 1443 * a value less than {@code 0} if {@code x < y}; and 1444 * a value greater than {@code 0} if {@code x > y} 1445 * @since 1.7 1446 */ 1447 public static int compare(long x, long y) { 1448 return (x < y) ? -1 : ((x == y) ? 0 : 1); 1449 } 1450 1451 /** 1452 * Compares two {@code long} values numerically treating the values 1453 * as unsigned. 1454 * 1455 * @param x the first {@code long} to compare 1456 * @param y the second {@code long} to compare 1457 * @return the value {@code 0} if {@code x == y}; a value less 1458 * than {@code 0} if {@code x < y} as unsigned values; and 1459 * a value greater than {@code 0} if {@code x > y} as 1460 * unsigned values 1461 * @since 1.8 1462 */ 1463 @IntrinsicCandidate 1464 public static int compareUnsigned(long x, long y) { 1465 return compare(x + MIN_VALUE, y + MIN_VALUE); 1466 } 1467 1468 1469 /** 1470 * Returns the unsigned quotient of dividing the first argument by 1471 * the second where each argument and the result is interpreted as 1472 * an unsigned value. 1473 * 1474 * <p>Note that in two's complement arithmetic, the three other 1475 * basic arithmetic operations of add, subtract, and multiply are 1476 * bit-wise identical if the two operands are regarded as both 1477 * being signed or both being unsigned. Therefore separate {@code 1478 * addUnsigned}, etc. methods are not provided. 1479 * 1480 * @param dividend the value to be divided 1481 * @param divisor the value doing the dividing 1482 * @return the unsigned quotient of the first argument divided by 1483 * the second argument 1484 * @see #remainderUnsigned 1485 * @since 1.8 1486 */ 1487 @IntrinsicCandidate 1488 public static long divideUnsigned(long dividend, long divisor) { 1489 /* See Hacker's Delight (2nd ed), section 9.3 */ 1490 if (divisor >= 0) { 1491 final long q = (dividend >>> 1) / divisor << 1; 1492 final long r = dividend - q * divisor; 1493 return q + ((r | ~(r - divisor)) >>> (Long.SIZE - 1)); 1494 } 1495 return (dividend & ~(dividend - divisor)) >>> (Long.SIZE - 1); 1496 } 1497 1498 /** 1499 * Returns the unsigned remainder from dividing the first argument 1500 * by the second where each argument and the result is interpreted 1501 * as an unsigned value. 1502 * 1503 * @param dividend the value to be divided 1504 * @param divisor the value doing the dividing 1505 * @return the unsigned remainder of the first argument divided by 1506 * the second argument 1507 * @see #divideUnsigned 1508 * @since 1.8 1509 */ 1510 @IntrinsicCandidate 1511 public static long remainderUnsigned(long dividend, long divisor) { 1512 /* See Hacker's Delight (2nd ed), section 9.3 */ 1513 if (divisor >= 0) { 1514 final long q = (dividend >>> 1) / divisor << 1; 1515 final long r = dividend - q * divisor; 1516 /* 1517 * Here, 0 <= r < 2 * divisor 1518 * (1) When 0 <= r < divisor, the remainder is simply r. 1519 * (2) Otherwise the remainder is r - divisor. 1520 * 1521 * In case (1), r - divisor < 0. Applying ~ produces a long with 1522 * sign bit 0, so >> produces 0. The returned value is thus r. 1523 * 1524 * In case (2), a similar reasoning shows that >> produces -1, 1525 * so the returned value is r - divisor. 1526 */ 1527 return r - ((~(r - divisor) >> (Long.SIZE - 1)) & divisor); 1528 } 1529 /* 1530 * (1) When dividend >= 0, the remainder is dividend. 1531 * (2) Otherwise 1532 * (2.1) When dividend < divisor, the remainder is dividend. 1533 * (2.2) Otherwise the remainder is dividend - divisor 1534 * 1535 * A reasoning similar to the above shows that the returned value 1536 * is as expected. 1537 */ 1538 return dividend - (((dividend & ~(dividend - divisor)) >> (Long.SIZE - 1)) & divisor); 1539 } 1540 1541 // Bit Twiddling 1542 1543 /** 1544 * The number of bits used to represent a {@code long} value in two's 1545 * complement binary form. 1546 * 1547 * @since 1.5 1548 */ 1549 @Native public static final int SIZE = 64; 1550 1551 /** 1552 * The number of bytes used to represent a {@code long} value in two's 1553 * complement binary form. 1554 * 1555 * @since 1.8 1556 */ 1557 public static final int BYTES = SIZE / Byte.SIZE; 1558 1559 /** 1560 * Returns a {@code long} value with at most a single one-bit, in the 1561 * position of the highest-order ("leftmost") one-bit in the specified 1562 * {@code long} value. Returns zero if the specified value has no 1563 * one-bits in its two's complement binary representation, that is, if it 1564 * is equal to zero. 1565 * 1566 * @param i the value whose highest one bit is to be computed 1567 * @return a {@code long} value with a single one-bit, in the position 1568 * of the highest-order one-bit in the specified value, or zero if 1569 * the specified value is itself equal to zero. 1570 * @since 1.5 1571 */ 1572 public static long highestOneBit(long i) { 1573 return i & (MIN_VALUE >>> numberOfLeadingZeros(i)); 1574 } 1575 1576 /** 1577 * Returns a {@code long} value with at most a single one-bit, in the 1578 * position of the lowest-order ("rightmost") one-bit in the specified 1579 * {@code long} value. Returns zero if the specified value has no 1580 * one-bits in its two's complement binary representation, that is, if it 1581 * is equal to zero. 1582 * 1583 * @param i the value whose lowest one bit is to be computed 1584 * @return a {@code long} value with a single one-bit, in the position 1585 * of the lowest-order one-bit in the specified value, or zero if 1586 * the specified value is itself equal to zero. 1587 * @since 1.5 1588 */ 1589 public static long lowestOneBit(long i) { 1590 // HD, Section 2-1 1591 return i & -i; 1592 } 1593 1594 /** 1595 * Returns the number of zero bits preceding the highest-order 1596 * ("leftmost") one-bit in the two's complement binary representation 1597 * of the specified {@code long} value. Returns 64 if the 1598 * specified value has no one-bits in its two's complement representation, 1599 * in other words if it is equal to zero. 1600 * 1601 * <p>Note that this method is closely related to the logarithm base 2. 1602 * For all positive {@code long} values x: 1603 * <ul> 1604 * <li>floor(log<sub>2</sub>(x)) = {@code 63 - numberOfLeadingZeros(x)} 1605 * <li>ceil(log<sub>2</sub>(x)) = {@code 64 - numberOfLeadingZeros(x - 1)} 1606 * </ul> 1607 * 1608 * @param i the value whose number of leading zeros is to be computed 1609 * @return the number of zero bits preceding the highest-order 1610 * ("leftmost") one-bit in the two's complement binary representation 1611 * of the specified {@code long} value, or 64 if the value 1612 * is equal to zero. 1613 * @since 1.5 1614 */ 1615 @IntrinsicCandidate 1616 public static int numberOfLeadingZeros(long i) { 1617 int x = (int)(i >>> 32); 1618 return x == 0 ? 32 + Integer.numberOfLeadingZeros((int)i) 1619 : Integer.numberOfLeadingZeros(x); 1620 } 1621 1622 /** 1623 * Returns the number of zero bits following the lowest-order ("rightmost") 1624 * one-bit in the two's complement binary representation of the specified 1625 * {@code long} value. Returns 64 if the specified value has no 1626 * one-bits in its two's complement representation, in other words if it is 1627 * equal to zero. 1628 * 1629 * @param i the value whose number of trailing zeros is to be computed 1630 * @return the number of zero bits following the lowest-order ("rightmost") 1631 * one-bit in the two's complement binary representation of the 1632 * specified {@code long} value, or 64 if the value is equal 1633 * to zero. 1634 * @since 1.5 1635 */ 1636 @IntrinsicCandidate 1637 public static int numberOfTrailingZeros(long i) { 1638 int x = (int)i; 1639 return x == 0 ? 32 + Integer.numberOfTrailingZeros((int)(i >>> 32)) 1640 : Integer.numberOfTrailingZeros(x); 1641 } 1642 1643 /** 1644 * Returns the number of one-bits in the two's complement binary 1645 * representation of the specified {@code long} value. This function is 1646 * sometimes referred to as the <i>population count</i>. 1647 * 1648 * @param i the value whose bits are to be counted 1649 * @return the number of one-bits in the two's complement binary 1650 * representation of the specified {@code long} value. 1651 * @since 1.5 1652 */ 1653 @IntrinsicCandidate 1654 public static int bitCount(long i) { 1655 // HD, Figure 5-2 1656 i = i - ((i >>> 1) & 0x5555555555555555L); 1657 i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L); 1658 i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL; 1659 i = i + (i >>> 8); 1660 i = i + (i >>> 16); 1661 i = i + (i >>> 32); 1662 return (int)i & 0x7f; 1663 } 1664 1665 /** 1666 * Returns the value obtained by rotating the two's complement binary 1667 * representation of the specified {@code long} value left by the 1668 * specified number of bits. (Bits shifted out of the left hand, or 1669 * high-order, side reenter on the right, or low-order.) 1670 * 1671 * <p>Note that left rotation with a negative distance is equivalent to 1672 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val, 1673 * distance)}. Note also that rotation by any multiple of 64 is a 1674 * no-op, so all but the last six bits of the rotation distance can be 1675 * ignored, even if the distance is negative: {@code rotateLeft(val, 1676 * distance) == rotateLeft(val, distance & 0x3F)}. 1677 * 1678 * @param i the value whose bits are to be rotated left 1679 * @param distance the number of bit positions to rotate left 1680 * @return the value obtained by rotating the two's complement binary 1681 * representation of the specified {@code long} value left by the 1682 * specified number of bits. 1683 * @since 1.5 1684 */ 1685 public static long rotateLeft(long i, int distance) { 1686 return (i << distance) | (i >>> -distance); 1687 } 1688 1689 /** 1690 * Returns the value obtained by rotating the two's complement binary 1691 * representation of the specified {@code long} value right by the 1692 * specified number of bits. (Bits shifted out of the right hand, or 1693 * low-order, side reenter on the left, or high-order.) 1694 * 1695 * <p>Note that right rotation with a negative distance is equivalent to 1696 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val, 1697 * distance)}. Note also that rotation by any multiple of 64 is a 1698 * no-op, so all but the last six bits of the rotation distance can be 1699 * ignored, even if the distance is negative: {@code rotateRight(val, 1700 * distance) == rotateRight(val, distance & 0x3F)}. 1701 * 1702 * @param i the value whose bits are to be rotated right 1703 * @param distance the number of bit positions to rotate right 1704 * @return the value obtained by rotating the two's complement binary 1705 * representation of the specified {@code long} value right by the 1706 * specified number of bits. 1707 * @since 1.5 1708 */ 1709 public static long rotateRight(long i, int distance) { 1710 return (i >>> distance) | (i << -distance); 1711 } 1712 1713 /** 1714 * Returns the value obtained by reversing the order of the bits in the 1715 * two's complement binary representation of the specified {@code long} 1716 * value. 1717 * 1718 * @param i the value to be reversed 1719 * @return the value obtained by reversing order of the bits in the 1720 * specified {@code long} value. 1721 * @since 1.5 1722 */ 1723 @IntrinsicCandidate 1724 public static long reverse(long i) { 1725 // HD, Figure 7-1 1726 i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L; 1727 i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L; 1728 i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL; 1729 1730 return reverseBytes(i); 1731 } 1732 1733 /** 1734 * Returns the value obtained by compressing the bits of the 1735 * specified {@code long} value, {@code i}, in accordance with 1736 * the specified bit mask. 1737 * <p> 1738 * For each one-bit value {@code mb} of the mask, from least 1739 * significant to most significant, the bit value of {@code i} at 1740 * the same bit location as {@code mb} is assigned to the compressed 1741 * value contiguously starting from the least significant bit location. 1742 * All the upper remaining bits of the compressed value are set 1743 * to zero. 1744 * 1745 * @apiNote 1746 * Consider the simple case of compressing the digits of a hexadecimal 1747 * value: 1748 * {@snippet lang="java" : 1749 * // Compressing drink to food 1750 * compress(0xCAFEBABEL, 0xFF00FFF0L) == 0xCABABL 1751 * } 1752 * Starting from the least significant hexadecimal digit at position 0 1753 * from the right, the mask {@code 0xFF00FFF0} selects hexadecimal digits 1754 * at positions 1, 2, 3, 6 and 7 of {@code 0xCAFEBABE}. The selected digits 1755 * occur in the resulting compressed value contiguously from digit position 1756 * 0 in the same order. 1757 * <p> 1758 * The following identities all return {@code true} and are helpful to 1759 * understand the behaviour of {@code compress}: 1760 * {@snippet lang="java" : 1761 * // Returns 1 if the bit at position n is one 1762 * compress(x, 1L << n) == (x >> n & 1) 1763 * 1764 * // Logical shift right 1765 * compress(x, -1L << n) == x >>> n 1766 * 1767 * // Any bits not covered by the mask are ignored 1768 * compress(x, m) == compress(x & m, m) 1769 * 1770 * // Compressing a value by itself 1771 * compress(m, m) == (m == -1 || m == 0) ? m : (1L << bitCount(m)) - 1 1772 * 1773 * // Expanding then compressing with the same mask 1774 * compress(expand(x, m), m) == x & compress(m, m) 1775 * } 1776 * <p> 1777 * The Sheep And Goats (SAG) operation (see Hacker's Delight, section 7.7) 1778 * can be implemented as follows: 1779 * {@snippet lang="java" : 1780 * long compressLeft(long i, long mask) { 1781 * // This implementation follows the description in Hacker's Delight which 1782 * // is informative. A more optimal implementation is: 1783 * // Long.compress(i, mask) << -Long.bitCount(mask) 1784 * return Long.reverse( 1785 * Long.compress(Long.reverse(i), Long.reverse(mask))); 1786 * } 1787 * 1788 * long sag(long i, long mask) { 1789 * return compressLeft(i, mask) | Long.compress(i, ~mask); 1790 * } 1791 * 1792 * // Separate the sheep from the goats 1793 * sag(0x00000000_CAFEBABEL, 0xFFFFFFFF_FF00FFF0L) == 0x00000000_CABABFEEL 1794 * } 1795 * 1796 * @param i the value whose bits are to be compressed 1797 * @param mask the bit mask 1798 * @return the compressed value 1799 * @see #expand 1800 * @since 19 1801 */ 1802 @IntrinsicCandidate 1803 public static long compress(long i, long mask) { 1804 // See Hacker's Delight (2nd ed) section 7.4 Compress, or Generalized Extract 1805 1806 i = i & mask; // Clear irrelevant bits 1807 long maskCount = ~mask << 1; // Count 0's to right 1808 1809 for (int j = 0; j < 6; j++) { 1810 // Parallel prefix 1811 // Mask prefix identifies bits of the mask that have an odd number of 0's to the right 1812 long maskPrefix = parallelSuffix(maskCount); 1813 // Bits to move 1814 long maskMove = maskPrefix & mask; 1815 // Compress mask 1816 mask = (mask ^ maskMove) | (maskMove >>> (1 << j)); 1817 // Bits of i to be moved 1818 long t = i & maskMove; 1819 // Compress i 1820 i = (i ^ t) | (t >>> (1 << j)); 1821 // Adjust the mask count by identifying bits that have 0 to the right 1822 maskCount = maskCount & ~maskPrefix; 1823 } 1824 return i; 1825 } 1826 1827 /** 1828 * Returns the value obtained by expanding the bits of the 1829 * specified {@code long} value, {@code i}, in accordance with 1830 * the specified bit mask. 1831 * <p> 1832 * For each one-bit value {@code mb} of the mask, from least 1833 * significant to most significant, the next contiguous bit value 1834 * of {@code i} starting at the least significant bit is assigned 1835 * to the expanded value at the same bit location as {@code mb}. 1836 * All other remaining bits of the expanded value are set to zero. 1837 * 1838 * @apiNote 1839 * Consider the simple case of expanding the digits of a hexadecimal 1840 * value: 1841 * {@snippet lang="java" : 1842 * expand(0x0000CABABL, 0xFF00FFF0L) == 0xCA00BAB0L 1843 * } 1844 * Starting from the least significant hexadecimal digit at position 0 1845 * from the right, the mask {@code 0xFF00FFF0} selects the first five 1846 * hexadecimal digits of {@code 0x0000CABAB}. The selected digits occur 1847 * in the resulting expanded value in order at positions 1, 2, 3, 6, and 7. 1848 * <p> 1849 * The following identities all return {@code true} and are helpful to 1850 * understand the behaviour of {@code expand}: 1851 * {@snippet lang="java" : 1852 * // Logically shift right the bit at position 0 1853 * expand(x, 1L << n) == (x & 1) << n 1854 * 1855 * // Logically shift right 1856 * expand(x, -1L << n) == x << n 1857 * 1858 * // Expanding all bits returns the mask 1859 * expand(-1L, m) == m 1860 * 1861 * // Any bits not covered by the mask are ignored 1862 * expand(x, m) == expand(x, m) & m 1863 * 1864 * // Compressing then expanding with the same mask 1865 * expand(compress(x, m), m) == x & m 1866 * } 1867 * <p> 1868 * The select operation for determining the position of the one-bit with 1869 * index {@code n} in a {@code long} value can be implemented as follows: 1870 * {@snippet lang="java" : 1871 * long select(long i, long n) { 1872 * // the one-bit in i (the mask) with index n 1873 * long nthBit = Long.expand(1L << n, i); 1874 * // the bit position of the one-bit with index n 1875 * return Long.numberOfTrailingZeros(nthBit); 1876 * } 1877 * 1878 * // The one-bit with index 0 is at bit position 1 1879 * select(0b10101010_10101010, 0) == 1 1880 * // The one-bit with index 3 is at bit position 7 1881 * select(0b10101010_10101010, 3) == 7 1882 * } 1883 * 1884 * @param i the value whose bits are to be expanded 1885 * @param mask the bit mask 1886 * @return the expanded value 1887 * @see #compress 1888 * @since 19 1889 */ 1890 @IntrinsicCandidate 1891 public static long expand(long i, long mask) { 1892 // Save original mask 1893 long originalMask = mask; 1894 // Count 0's to right 1895 long maskCount = ~mask << 1; 1896 long maskPrefix = parallelSuffix(maskCount); 1897 // Bits to move 1898 long maskMove1 = maskPrefix & mask; 1899 // Compress mask 1900 mask = (mask ^ maskMove1) | (maskMove1 >>> (1 << 0)); 1901 maskCount = maskCount & ~maskPrefix; 1902 1903 maskPrefix = parallelSuffix(maskCount); 1904 // Bits to move 1905 long maskMove2 = maskPrefix & mask; 1906 // Compress mask 1907 mask = (mask ^ maskMove2) | (maskMove2 >>> (1 << 1)); 1908 maskCount = maskCount & ~maskPrefix; 1909 1910 maskPrefix = parallelSuffix(maskCount); 1911 // Bits to move 1912 long maskMove3 = maskPrefix & mask; 1913 // Compress mask 1914 mask = (mask ^ maskMove3) | (maskMove3 >>> (1 << 2)); 1915 maskCount = maskCount & ~maskPrefix; 1916 1917 maskPrefix = parallelSuffix(maskCount); 1918 // Bits to move 1919 long maskMove4 = maskPrefix & mask; 1920 // Compress mask 1921 mask = (mask ^ maskMove4) | (maskMove4 >>> (1 << 3)); 1922 maskCount = maskCount & ~maskPrefix; 1923 1924 maskPrefix = parallelSuffix(maskCount); 1925 // Bits to move 1926 long maskMove5 = maskPrefix & mask; 1927 // Compress mask 1928 mask = (mask ^ maskMove5) | (maskMove5 >>> (1 << 4)); 1929 maskCount = maskCount & ~maskPrefix; 1930 1931 maskPrefix = parallelSuffix(maskCount); 1932 // Bits to move 1933 long maskMove6 = maskPrefix & mask; 1934 1935 long t = i << (1 << 5); 1936 i = (i & ~maskMove6) | (t & maskMove6); 1937 t = i << (1 << 4); 1938 i = (i & ~maskMove5) | (t & maskMove5); 1939 t = i << (1 << 3); 1940 i = (i & ~maskMove4) | (t & maskMove4); 1941 t = i << (1 << 2); 1942 i = (i & ~maskMove3) | (t & maskMove3); 1943 t = i << (1 << 1); 1944 i = (i & ~maskMove2) | (t & maskMove2); 1945 t = i << (1 << 0); 1946 i = (i & ~maskMove1) | (t & maskMove1); 1947 1948 // Clear irrelevant bits 1949 return i & originalMask; 1950 } 1951 1952 @ForceInline 1953 private static long parallelSuffix(long maskCount) { 1954 long maskPrefix = maskCount ^ (maskCount << 1); 1955 maskPrefix = maskPrefix ^ (maskPrefix << 2); 1956 maskPrefix = maskPrefix ^ (maskPrefix << 4); 1957 maskPrefix = maskPrefix ^ (maskPrefix << 8); 1958 maskPrefix = maskPrefix ^ (maskPrefix << 16); 1959 maskPrefix = maskPrefix ^ (maskPrefix << 32); 1960 return maskPrefix; 1961 } 1962 1963 /** 1964 * Returns the signum function of the specified {@code long} value. (The 1965 * return value is -1 if the specified value is negative; 0 if the 1966 * specified value is zero; and 1 if the specified value is positive.) 1967 * 1968 * @param i the value whose signum is to be computed 1969 * @return the signum function of the specified {@code long} value. 1970 * @since 1.5 1971 */ 1972 public static int signum(long i) { 1973 // HD, Section 2-7 1974 return (int) ((i >> 63) | (-i >>> 63)); 1975 } 1976 1977 /** 1978 * Returns the value obtained by reversing the order of the bytes in the 1979 * two's complement representation of the specified {@code long} value. 1980 * 1981 * @param i the value whose bytes are to be reversed 1982 * @return the value obtained by reversing the bytes in the specified 1983 * {@code long} value. 1984 * @since 1.5 1985 */ 1986 @IntrinsicCandidate 1987 public static long reverseBytes(long i) { 1988 i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL; 1989 return (i << 48) | ((i & 0xffff0000L) << 16) | 1990 ((i >>> 16) & 0xffff0000L) | (i >>> 48); 1991 } 1992 1993 /** 1994 * Adds two {@code long} values together as per the + operator. 1995 * 1996 * @param a the first operand 1997 * @param b the second operand 1998 * @return the sum of {@code a} and {@code b} 1999 * @see java.util.function.BinaryOperator 2000 * @since 1.8 2001 */ 2002 public static long sum(long a, long b) { 2003 return a + b; 2004 } 2005 2006 /** 2007 * Returns the greater of two {@code long} values 2008 * as if by calling {@link Math#max(long, long) Math.max}. 2009 * 2010 * @param a the first operand 2011 * @param b the second operand 2012 * @return the greater of {@code a} and {@code b} 2013 * @see java.util.function.BinaryOperator 2014 * @since 1.8 2015 */ 2016 public static long max(long a, long b) { 2017 return Math.max(a, b); 2018 } 2019 2020 /** 2021 * Returns the smaller of two {@code long} values 2022 * as if by calling {@link Math#min(long, long) Math.min}. 2023 * 2024 * @param a the first operand 2025 * @param b the second operand 2026 * @return the smaller of {@code a} and {@code b} 2027 * @see java.util.function.BinaryOperator 2028 * @since 1.8 2029 */ 2030 public static long min(long a, long b) { 2031 return Math.min(a, b); 2032 } 2033 2034 /** 2035 * Returns an {@link Optional} containing the nominal descriptor for this 2036 * instance, which is the instance itself. 2037 * 2038 * @return an {@link Optional} describing the {@linkplain Long} instance 2039 * @since 12 2040 */ 2041 @Override 2042 public Optional<Long> describeConstable() { 2043 return Optional.of(this); 2044 } 2045 2046 /** 2047 * Resolves this instance as a {@link ConstantDesc}, the result of which is 2048 * the instance itself. 2049 * 2050 * @param lookup ignored 2051 * @return the {@linkplain Long} instance 2052 * @since 12 2053 */ 2054 @Override 2055 public Long resolveConstantDesc(MethodHandles.Lookup lookup) { 2056 return this; 2057 } 2058 2059 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 2060 @java.io.Serial 2061 @Native private static final long serialVersionUID = 4290774380558885855L; 2062 }