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