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