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