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