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 @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 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) { 1249 return value == ((Long)obj).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 * @throws SecurityException for the same reasons as 1280 * {@link System#getProperty(String) System.getProperty} 1281 * @see java.lang.System#getProperty(java.lang.String) 1282 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1283 */ 1284 public static Long getLong(String nm) { 1285 return getLong(nm, null); 1286 } 1287 1288 /** 1289 * Determines the {@code long} value of the system property 1290 * with the specified name. 1291 * 1292 * <p>The first argument is treated as the name of a system 1293 * property. System properties are accessible through the {@link 1294 * java.lang.System#getProperty(java.lang.String)} method. The 1295 * string value of this property is then interpreted as a {@code 1296 * long} value using the grammar supported by {@link Long#decode decode} 1297 * and a {@code Long} object representing this value is returned. 1298 * 1299 * <p>The second argument is the default value. A {@code Long} object 1300 * that represents the value of the second argument is returned if there 1301 * is no property of the specified name, if the property does not have 1302 * the correct numeric format, or if the specified name is empty or null. 1303 * 1304 * <p>In other words, this method returns a {@code Long} object equal 1305 * to the value of: 1306 * 1307 * <blockquote> 1308 * {@code getLong(nm, Long.valueOf(val))} 1309 * </blockquote> 1310 * 1311 * but in practice it may be implemented in a manner such as: 1312 * 1313 * <blockquote><pre> 1314 * Long result = getLong(nm, null); 1315 * return (result == null) ? Long.valueOf(val) : result; 1316 * </pre></blockquote> 1317 * 1318 * to avoid the unnecessary allocation of a {@code Long} object when 1319 * the default value is not needed. 1320 * 1321 * @param nm property name. 1322 * @param val default value. 1323 * @return the {@code Long} value of the property. 1324 * @throws SecurityException for the same reasons as 1325 * {@link System#getProperty(String) System.getProperty} 1326 * @see java.lang.System#getProperty(java.lang.String) 1327 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1328 */ 1329 public static Long getLong(String nm, long val) { 1330 Long result = Long.getLong(nm, null); 1331 return (result == null) ? Long.valueOf(val) : result; 1332 } 1333 1334 /** 1335 * Returns the {@code long} value of the system property with 1336 * the specified name. The first argument is treated as the name 1337 * of a system property. System properties are accessible through 1338 * the {@link java.lang.System#getProperty(java.lang.String)} 1339 * method. The string value of this property is then interpreted 1340 * as a {@code long} value, as per the 1341 * {@link Long#decode decode} method, and a {@code Long} object 1342 * representing this value is returned; in summary: 1343 * 1344 * <ul> 1345 * <li>If the property value begins with the two ASCII characters 1346 * {@code 0x} or the ASCII character {@code #}, not followed by 1347 * a minus sign, then the rest of it is parsed as a hexadecimal integer 1348 * exactly as for the method {@link #valueOf(java.lang.String, int)} 1349 * with radix 16. 1350 * <li>If the property value begins with the ASCII character 1351 * {@code 0} followed by another character, it is parsed as 1352 * an octal integer exactly as by the method {@link 1353 * #valueOf(java.lang.String, int)} with radix 8. 1354 * <li>Otherwise the property value is parsed as a decimal 1355 * integer exactly as by the method 1356 * {@link #valueOf(java.lang.String, int)} with radix 10. 1357 * </ul> 1358 * 1359 * <p>Note that, in every case, neither {@code L} 1360 * ({@code '\u005Cu004C'}) nor {@code l} 1361 * ({@code '\u005Cu006C'}) is permitted to appear at the end 1362 * of the property value as a type indicator, as would be 1363 * permitted in Java programming language source code. 1364 * 1365 * <p>The second argument is the default value. The default value is 1366 * returned if there is no property of the specified name, if the 1367 * property does not have the correct numeric format, or if the 1368 * specified name is empty or {@code null}. 1369 * 1370 * @param nm property name. 1371 * @param val default value. 1372 * @return the {@code Long} value of the property. 1373 * @throws SecurityException for the same reasons as 1374 * {@link System#getProperty(String) System.getProperty} 1375 * @see System#getProperty(java.lang.String) 1376 * @see System#getProperty(java.lang.String, java.lang.String) 1377 */ 1378 public static Long getLong(String nm, Long val) { 1379 String v = null; 1380 try { 1381 v = System.getProperty(nm); 1382 } catch (IllegalArgumentException | NullPointerException e) { 1383 } 1384 if (v != null) { 1385 try { 1386 return Long.decode(v); 1387 } catch (NumberFormatException e) { 1388 } 1389 } 1390 return val; 1391 } 1392 1393 /** 1394 * Compares two {@code Long} objects numerically. 1395 * 1396 * @param anotherLong the {@code Long} to be compared. 1397 * @return the value {@code 0} if this {@code Long} is 1398 * equal to the argument {@code Long}; a value less than 1399 * {@code 0} if this {@code Long} is numerically less 1400 * than the argument {@code Long}; and a value greater 1401 * than {@code 0} if this {@code Long} is numerically 1402 * greater than the argument {@code Long} (signed 1403 * comparison). 1404 * @since 1.2 1405 */ 1406 public int compareTo(Long anotherLong) { 1407 return compare(this.value, anotherLong.value); 1408 } 1409 1410 /** 1411 * Compares two {@code long} values numerically. 1412 * The value returned is identical to what would be returned by: 1413 * <pre> 1414 * Long.valueOf(x).compareTo(Long.valueOf(y)) 1415 * </pre> 1416 * 1417 * @param x the first {@code long} to compare 1418 * @param y the second {@code long} to compare 1419 * @return the value {@code 0} if {@code x == y}; 1420 * a value less than {@code 0} if {@code x < y}; and 1421 * a value greater than {@code 0} if {@code x > y} 1422 * @since 1.7 1423 */ 1424 public static int compare(long x, long y) { 1425 return (x < y) ? -1 : ((x == y) ? 0 : 1); 1426 } 1427 1428 /** 1429 * Compares two {@code long} values numerically treating the values 1430 * as unsigned. 1431 * 1432 * @param x the first {@code long} to compare 1433 * @param y the second {@code long} to compare 1434 * @return the value {@code 0} if {@code x == y}; a value less 1435 * than {@code 0} if {@code x < y} as unsigned values; and 1436 * a value greater than {@code 0} if {@code x > y} as 1437 * unsigned values 1438 * @since 1.8 1439 */ 1440 @IntrinsicCandidate 1441 public static int compareUnsigned(long x, long y) { 1442 return compare(x + MIN_VALUE, y + MIN_VALUE); 1443 } 1444 1445 1446 /** 1447 * Returns the unsigned quotient of dividing the first argument by 1448 * the second where each argument and the result is interpreted as 1449 * an unsigned value. 1450 * 1451 * <p>Note that in two's complement arithmetic, the three other 1452 * basic arithmetic operations of add, subtract, and multiply are 1453 * bit-wise identical if the two operands are regarded as both 1454 * being signed or both being unsigned. Therefore separate {@code 1455 * addUnsigned}, etc. methods are not provided. 1456 * 1457 * @param dividend the value to be divided 1458 * @param divisor the value doing the dividing 1459 * @return the unsigned quotient of the first argument divided by 1460 * the second argument 1461 * @see #remainderUnsigned 1462 * @since 1.8 1463 */ 1464 @IntrinsicCandidate 1465 public static long divideUnsigned(long dividend, long divisor) { 1466 /* See Hacker's Delight (2nd ed), section 9.3 */ 1467 if (divisor >= 0) { 1468 final long q = (dividend >>> 1) / divisor << 1; 1469 final long r = dividend - q * divisor; 1470 return q + ((r | ~(r - divisor)) >>> (Long.SIZE - 1)); 1471 } 1472 return (dividend & ~(dividend - divisor)) >>> (Long.SIZE - 1); 1473 } 1474 1475 /** 1476 * Returns the unsigned remainder from dividing the first argument 1477 * by the second where each argument and the result is interpreted 1478 * as an unsigned value. 1479 * 1480 * @param dividend the value to be divided 1481 * @param divisor the value doing the dividing 1482 * @return the unsigned remainder of the first argument divided by 1483 * the second argument 1484 * @see #divideUnsigned 1485 * @since 1.8 1486 */ 1487 @IntrinsicCandidate 1488 public static long remainderUnsigned(long dividend, long divisor) { 1489 /* See Hacker's Delight (2nd ed), section 9.3 */ 1490 if (divisor >= 0) { 1491 final long q = (dividend >>> 1) / divisor << 1; 1492 final long r = dividend - q * divisor; 1493 /* 1494 * Here, 0 <= r < 2 * divisor 1495 * (1) When 0 <= r < divisor, the remainder is simply r. 1496 * (2) Otherwise the remainder is r - divisor. 1497 * 1498 * In case (1), r - divisor < 0. Applying ~ produces a long with 1499 * sign bit 0, so >> produces 0. The returned value is thus r. 1500 * 1501 * In case (2), a similar reasoning shows that >> produces -1, 1502 * so the returned value is r - divisor. 1503 */ 1504 return r - ((~(r - divisor) >> (Long.SIZE - 1)) & divisor); 1505 } 1506 /* 1507 * (1) When dividend >= 0, the remainder is dividend. 1508 * (2) Otherwise 1509 * (2.1) When dividend < divisor, the remainder is dividend. 1510 * (2.2) Otherwise the remainder is dividend - divisor 1511 * 1512 * A reasoning similar to the above shows that the returned value 1513 * is as expected. 1514 */ 1515 return dividend - (((dividend & ~(dividend - divisor)) >> (Long.SIZE - 1)) & divisor); 1516 } 1517 1518 // Bit Twiddling 1519 1520 /** 1521 * The number of bits used to represent a {@code long} value in two's 1522 * complement binary form. 1523 * 1524 * @since 1.5 1525 */ 1526 @Native public static final int SIZE = 64; 1527 1528 /** 1529 * The number of bytes used to represent a {@code long} value in two's 1530 * complement binary form. 1531 * 1532 * @since 1.8 1533 */ 1534 public static final int BYTES = SIZE / Byte.SIZE; 1535 1536 /** 1537 * Returns a {@code long} value with at most a single one-bit, in the 1538 * position of the highest-order ("leftmost") one-bit in the specified 1539 * {@code long} value. Returns zero if the specified value has no 1540 * one-bits in its two's complement binary representation, that is, if it 1541 * is equal to zero. 1542 * 1543 * @param i the value whose highest one bit is to be computed 1544 * @return a {@code long} value with a single one-bit, in the position 1545 * of the highest-order one-bit in the specified value, or zero if 1546 * the specified value is itself equal to zero. 1547 * @since 1.5 1548 */ 1549 public static long highestOneBit(long i) { 1550 return i & (MIN_VALUE >>> numberOfLeadingZeros(i)); 1551 } 1552 1553 /** 1554 * Returns a {@code long} value with at most a single one-bit, in the 1555 * position of the lowest-order ("rightmost") one-bit in the specified 1556 * {@code long} value. Returns zero if the specified value has no 1557 * one-bits in its two's complement binary representation, that is, if it 1558 * is equal to zero. 1559 * 1560 * @param i the value whose lowest one bit is to be computed 1561 * @return a {@code long} value with a single one-bit, in the position 1562 * of the lowest-order one-bit in the specified value, or zero if 1563 * the specified value is itself equal to zero. 1564 * @since 1.5 1565 */ 1566 public static long lowestOneBit(long i) { 1567 // HD, Section 2-1 1568 return i & -i; 1569 } 1570 1571 /** 1572 * Returns the number of zero bits preceding the highest-order 1573 * ("leftmost") one-bit in the two's complement binary representation 1574 * of the specified {@code long} value. Returns 64 if the 1575 * specified value has no one-bits in its two's complement representation, 1576 * in other words if it is equal to zero. 1577 * 1578 * <p>Note that this method is closely related to the logarithm base 2. 1579 * For all positive {@code long} values x: 1580 * <ul> 1581 * <li>floor(log<sub>2</sub>(x)) = {@code 63 - numberOfLeadingZeros(x)} 1582 * <li>ceil(log<sub>2</sub>(x)) = {@code 64 - numberOfLeadingZeros(x - 1)} 1583 * </ul> 1584 * 1585 * @param i the value whose number of leading zeros is to be computed 1586 * @return the number of zero bits preceding the highest-order 1587 * ("leftmost") one-bit in the two's complement binary representation 1588 * of the specified {@code long} value, or 64 if the value 1589 * is equal to zero. 1590 * @since 1.5 1591 */ 1592 @IntrinsicCandidate 1593 public static int numberOfLeadingZeros(long i) { 1594 int x = (int)(i >>> 32); 1595 return x == 0 ? 32 + Integer.numberOfLeadingZeros((int)i) 1596 : Integer.numberOfLeadingZeros(x); 1597 } 1598 1599 /** 1600 * Returns the number of zero bits following the lowest-order ("rightmost") 1601 * one-bit in the two's complement binary representation of the specified 1602 * {@code long} value. Returns 64 if the specified value has no 1603 * one-bits in its two's complement representation, in other words if it is 1604 * equal to zero. 1605 * 1606 * @param i the value whose number of trailing zeros is to be computed 1607 * @return the number of zero bits following the lowest-order ("rightmost") 1608 * one-bit in the two's complement binary representation of the 1609 * specified {@code long} value, or 64 if the value is equal 1610 * to zero. 1611 * @since 1.5 1612 */ 1613 @IntrinsicCandidate 1614 public static int numberOfTrailingZeros(long i) { 1615 int x = (int)i; 1616 return x == 0 ? 32 + Integer.numberOfTrailingZeros((int)(i >>> 32)) 1617 : Integer.numberOfTrailingZeros(x); 1618 } 1619 1620 /** 1621 * Returns the number of one-bits in the two's complement binary 1622 * representation of the specified {@code long} value. This function is 1623 * sometimes referred to as the <i>population count</i>. 1624 * 1625 * @param i the value whose bits are to be counted 1626 * @return the number of one-bits in the two's complement binary 1627 * representation of the specified {@code long} value. 1628 * @since 1.5 1629 */ 1630 @IntrinsicCandidate 1631 public static int bitCount(long i) { 1632 // HD, Figure 5-2 1633 i = i - ((i >>> 1) & 0x5555555555555555L); 1634 i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L); 1635 i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL; 1636 i = i + (i >>> 8); 1637 i = i + (i >>> 16); 1638 i = i + (i >>> 32); 1639 return (int)i & 0x7f; 1640 } 1641 1642 /** 1643 * Returns the value obtained by rotating the two's complement binary 1644 * representation of the specified {@code long} value left by the 1645 * specified number of bits. (Bits shifted out of the left hand, or 1646 * high-order, side reenter on the right, or low-order.) 1647 * 1648 * <p>Note that left rotation with a negative distance is equivalent to 1649 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val, 1650 * distance)}. Note also that rotation by any multiple of 64 is a 1651 * no-op, so all but the last six bits of the rotation distance can be 1652 * ignored, even if the distance is negative: {@code rotateLeft(val, 1653 * distance) == rotateLeft(val, distance & 0x3F)}. 1654 * 1655 * @param i the value whose bits are to be rotated left 1656 * @param distance the number of bit positions to rotate left 1657 * @return the value obtained by rotating the two's complement binary 1658 * representation of the specified {@code long} value left by the 1659 * specified number of bits. 1660 * @since 1.5 1661 */ 1662 public static long rotateLeft(long i, int distance) { 1663 return (i << distance) | (i >>> -distance); 1664 } 1665 1666 /** 1667 * Returns the value obtained by rotating the two's complement binary 1668 * representation of the specified {@code long} value right by the 1669 * specified number of bits. (Bits shifted out of the right hand, or 1670 * low-order, side reenter on the left, or high-order.) 1671 * 1672 * <p>Note that right rotation with a negative distance is equivalent to 1673 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val, 1674 * distance)}. Note also that rotation by any multiple of 64 is a 1675 * no-op, so all but the last six bits of the rotation distance can be 1676 * ignored, even if the distance is negative: {@code rotateRight(val, 1677 * distance) == rotateRight(val, distance & 0x3F)}. 1678 * 1679 * @param i the value whose bits are to be rotated right 1680 * @param distance the number of bit positions to rotate right 1681 * @return the value obtained by rotating the two's complement binary 1682 * representation of the specified {@code long} value right by the 1683 * specified number of bits. 1684 * @since 1.5 1685 */ 1686 public static long rotateRight(long i, int distance) { 1687 return (i >>> distance) | (i << -distance); 1688 } 1689 1690 /** 1691 * Returns the value obtained by reversing the order of the bits in the 1692 * two's complement binary representation of the specified {@code long} 1693 * value. 1694 * 1695 * @param i the value to be reversed 1696 * @return the value obtained by reversing order of the bits in the 1697 * specified {@code long} value. 1698 * @since 1.5 1699 */ 1700 @IntrinsicCandidate 1701 public static long reverse(long i) { 1702 // HD, Figure 7-1 1703 i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L; 1704 i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L; 1705 i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL; 1706 1707 return reverseBytes(i); 1708 } 1709 1710 /** 1711 * Returns the value obtained by compressing the bits of the 1712 * specified {@code long} value, {@code i}, in accordance with 1713 * the specified bit mask. 1714 * <p> 1715 * For each one-bit value {@code mb} of the mask, from least 1716 * significant to most significant, the bit value of {@code i} at 1717 * the same bit location as {@code mb} is assigned to the compressed 1718 * value contiguously starting from the least significant bit location. 1719 * All the upper remaining bits of the compressed value are set 1720 * to zero. 1721 * 1722 * @apiNote 1723 * Consider the simple case of compressing the digits of a hexadecimal 1724 * value: 1725 * {@snippet lang="java" : 1726 * // Compressing drink to food 1727 * compress(0xCAFEBABEL, 0xFF00FFF0L) == 0xCABABL 1728 * } 1729 * Starting from the least significant hexadecimal digit at position 0 1730 * from the right, the mask {@code 0xFF00FFF0} selects hexadecimal digits 1731 * at positions 1, 2, 3, 6 and 7 of {@code 0xCAFEBABE}. The selected digits 1732 * occur in the resulting compressed value contiguously from digit position 1733 * 0 in the same order. 1734 * <p> 1735 * The following identities all return {@code true} and are helpful to 1736 * understand the behaviour of {@code compress}: 1737 * {@snippet lang="java" : 1738 * // Returns 1 if the bit at position n is one 1739 * compress(x, 1L << n) == (x >> n & 1) 1740 * 1741 * // Logical shift right 1742 * compress(x, -1L << n) == x >>> n 1743 * 1744 * // Any bits not covered by the mask are ignored 1745 * compress(x, m) == compress(x & m, m) 1746 * 1747 * // Compressing a value by itself 1748 * compress(m, m) == (m == -1 || m == 0) ? m : (1L << bitCount(m)) - 1 1749 * 1750 * // Expanding then compressing with the same mask 1751 * compress(expand(x, m), m) == x & compress(m, m) 1752 * } 1753 * <p> 1754 * The Sheep And Goats (SAG) operation (see Hacker's Delight, Second Edition, section 7.7) 1755 * can be implemented as follows: 1756 * {@snippet lang="java" : 1757 * long compressLeft(long i, long mask) { 1758 * // This implementation follows the description in Hacker's Delight which 1759 * // is informative. A more optimal implementation is: 1760 * // Long.compress(i, mask) << -Long.bitCount(mask) 1761 * return Long.reverse( 1762 * Long.compress(Long.reverse(i), Long.reverse(mask))); 1763 * } 1764 * 1765 * long sag(long i, long mask) { 1766 * return compressLeft(i, mask) | Long.compress(i, ~mask); 1767 * } 1768 * 1769 * // Separate the sheep from the goats 1770 * sag(0x00000000_CAFEBABEL, 0xFFFFFFFF_FF00FFF0L) == 0x00000000_CABABFEEL 1771 * } 1772 * 1773 * @param i the value whose bits are to be compressed 1774 * @param mask the bit mask 1775 * @return the compressed value 1776 * @see #expand 1777 * @since 19 1778 */ 1779 @IntrinsicCandidate 1780 public static long compress(long i, long mask) { 1781 // See Hacker's Delight (2nd ed) section 7.4 Compress, or Generalized Extract 1782 1783 i = i & mask; // Clear irrelevant bits 1784 long maskCount = ~mask << 1; // Count 0's to right 1785 1786 for (int j = 0; j < 6; j++) { 1787 // Parallel prefix 1788 // Mask prefix identifies bits of the mask that have an odd number of 0's to the right 1789 long maskPrefix = parallelSuffix(maskCount); 1790 // Bits to move 1791 long maskMove = maskPrefix & mask; 1792 // Compress mask 1793 mask = (mask ^ maskMove) | (maskMove >>> (1 << j)); 1794 // Bits of i to be moved 1795 long t = i & maskMove; 1796 // Compress i 1797 i = (i ^ t) | (t >>> (1 << j)); 1798 // Adjust the mask count by identifying bits that have 0 to the right 1799 maskCount = maskCount & ~maskPrefix; 1800 } 1801 return i; 1802 } 1803 1804 /** 1805 * Returns the value obtained by expanding the bits of the 1806 * specified {@code long} value, {@code i}, in accordance with 1807 * the specified bit mask. 1808 * <p> 1809 * For each one-bit value {@code mb} of the mask, from least 1810 * significant to most significant, the next contiguous bit value 1811 * of {@code i} starting at the least significant bit is assigned 1812 * to the expanded value at the same bit location as {@code mb}. 1813 * All other remaining bits of the expanded value are set to zero. 1814 * 1815 * @apiNote 1816 * Consider the simple case of expanding the digits of a hexadecimal 1817 * value: 1818 * {@snippet lang="java" : 1819 * expand(0x0000CABABL, 0xFF00FFF0L) == 0xCA00BAB0L 1820 * } 1821 * Starting from the least significant hexadecimal digit at position 0 1822 * from the right, the mask {@code 0xFF00FFF0} selects the first five 1823 * hexadecimal digits of {@code 0x0000CABAB}. The selected digits occur 1824 * in the resulting expanded value in order at positions 1, 2, 3, 6, and 7. 1825 * <p> 1826 * The following identities all return {@code true} and are helpful to 1827 * understand the behaviour of {@code expand}: 1828 * {@snippet lang="java" : 1829 * // Logically shift right the bit at position 0 1830 * expand(x, 1L << n) == (x & 1) << n 1831 * 1832 * // Logically shift right 1833 * expand(x, -1L << n) == x << n 1834 * 1835 * // Expanding all bits returns the mask 1836 * expand(-1L, m) == m 1837 * 1838 * // Any bits not covered by the mask are ignored 1839 * expand(x, m) == expand(x, m) & m 1840 * 1841 * // Compressing then expanding with the same mask 1842 * expand(compress(x, m), m) == x & m 1843 * } 1844 * <p> 1845 * The select operation for determining the position of the one-bit with 1846 * index {@code n} in a {@code long} value can be implemented as follows: 1847 * {@snippet lang="java" : 1848 * long select(long i, long n) { 1849 * // the one-bit in i (the mask) with index n 1850 * long nthBit = Long.expand(1L << n, i); 1851 * // the bit position of the one-bit with index n 1852 * return Long.numberOfTrailingZeros(nthBit); 1853 * } 1854 * 1855 * // The one-bit with index 0 is at bit position 1 1856 * select(0b10101010_10101010, 0) == 1 1857 * // The one-bit with index 3 is at bit position 7 1858 * select(0b10101010_10101010, 3) == 7 1859 * } 1860 * 1861 * @param i the value whose bits are to be expanded 1862 * @param mask the bit mask 1863 * @return the expanded value 1864 * @see #compress 1865 * @since 19 1866 */ 1867 @IntrinsicCandidate 1868 public static long expand(long i, long mask) { 1869 // Save original mask 1870 long originalMask = mask; 1871 // Count 0's to right 1872 long maskCount = ~mask << 1; 1873 long maskPrefix = parallelSuffix(maskCount); 1874 // Bits to move 1875 long maskMove1 = maskPrefix & mask; 1876 // Compress mask 1877 mask = (mask ^ maskMove1) | (maskMove1 >>> (1 << 0)); 1878 maskCount = maskCount & ~maskPrefix; 1879 1880 maskPrefix = parallelSuffix(maskCount); 1881 // Bits to move 1882 long maskMove2 = maskPrefix & mask; 1883 // Compress mask 1884 mask = (mask ^ maskMove2) | (maskMove2 >>> (1 << 1)); 1885 maskCount = maskCount & ~maskPrefix; 1886 1887 maskPrefix = parallelSuffix(maskCount); 1888 // Bits to move 1889 long maskMove3 = maskPrefix & mask; 1890 // Compress mask 1891 mask = (mask ^ maskMove3) | (maskMove3 >>> (1 << 2)); 1892 maskCount = maskCount & ~maskPrefix; 1893 1894 maskPrefix = parallelSuffix(maskCount); 1895 // Bits to move 1896 long maskMove4 = maskPrefix & mask; 1897 // Compress mask 1898 mask = (mask ^ maskMove4) | (maskMove4 >>> (1 << 3)); 1899 maskCount = maskCount & ~maskPrefix; 1900 1901 maskPrefix = parallelSuffix(maskCount); 1902 // Bits to move 1903 long maskMove5 = maskPrefix & mask; 1904 // Compress mask 1905 mask = (mask ^ maskMove5) | (maskMove5 >>> (1 << 4)); 1906 maskCount = maskCount & ~maskPrefix; 1907 1908 maskPrefix = parallelSuffix(maskCount); 1909 // Bits to move 1910 long maskMove6 = maskPrefix & mask; 1911 1912 long t = i << (1 << 5); 1913 i = (i & ~maskMove6) | (t & maskMove6); 1914 t = i << (1 << 4); 1915 i = (i & ~maskMove5) | (t & maskMove5); 1916 t = i << (1 << 3); 1917 i = (i & ~maskMove4) | (t & maskMove4); 1918 t = i << (1 << 2); 1919 i = (i & ~maskMove3) | (t & maskMove3); 1920 t = i << (1 << 1); 1921 i = (i & ~maskMove2) | (t & maskMove2); 1922 t = i << (1 << 0); 1923 i = (i & ~maskMove1) | (t & maskMove1); 1924 1925 // Clear irrelevant bits 1926 return i & originalMask; 1927 } 1928 1929 @ForceInline 1930 private static long parallelSuffix(long maskCount) { 1931 long maskPrefix = maskCount ^ (maskCount << 1); 1932 maskPrefix = maskPrefix ^ (maskPrefix << 2); 1933 maskPrefix = maskPrefix ^ (maskPrefix << 4); 1934 maskPrefix = maskPrefix ^ (maskPrefix << 8); 1935 maskPrefix = maskPrefix ^ (maskPrefix << 16); 1936 maskPrefix = maskPrefix ^ (maskPrefix << 32); 1937 return maskPrefix; 1938 } 1939 1940 /** 1941 * Returns the signum function of the specified {@code long} value. (The 1942 * return value is -1 if the specified value is negative; 0 if the 1943 * specified value is zero; and 1 if the specified value is positive.) 1944 * 1945 * @param i the value whose signum is to be computed 1946 * @return the signum function of the specified {@code long} value. 1947 * @since 1.5 1948 */ 1949 public static int signum(long i) { 1950 // HD, Section 2-7 1951 return (int) ((i >> 63) | (-i >>> 63)); 1952 } 1953 1954 /** 1955 * Returns the value obtained by reversing the order of the bytes in the 1956 * two's complement representation of the specified {@code long} value. 1957 * 1958 * @param i the value whose bytes are to be reversed 1959 * @return the value obtained by reversing the bytes in the specified 1960 * {@code long} value. 1961 * @since 1.5 1962 */ 1963 @IntrinsicCandidate 1964 public static long reverseBytes(long i) { 1965 i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL; 1966 return (i << 48) | ((i & 0xffff0000L) << 16) | 1967 ((i >>> 16) & 0xffff0000L) | (i >>> 48); 1968 } 1969 1970 /** 1971 * Adds two {@code long} values together as per the + operator. 1972 * 1973 * @param a the first operand 1974 * @param b the second operand 1975 * @return the sum of {@code a} and {@code b} 1976 * @see java.util.function.BinaryOperator 1977 * @since 1.8 1978 */ 1979 public static long sum(long a, long b) { 1980 return a + b; 1981 } 1982 1983 /** 1984 * Returns the greater of two {@code long} values 1985 * as if by calling {@link Math#max(long, long) Math.max}. 1986 * 1987 * @param a the first operand 1988 * @param b the second operand 1989 * @return the greater of {@code a} and {@code b} 1990 * @see java.util.function.BinaryOperator 1991 * @since 1.8 1992 */ 1993 public static long max(long a, long b) { 1994 return Math.max(a, b); 1995 } 1996 1997 /** 1998 * Returns the smaller of two {@code long} values 1999 * as if by calling {@link Math#min(long, long) Math.min}. 2000 * 2001 * @param a the first operand 2002 * @param b the second operand 2003 * @return the smaller of {@code a} and {@code b} 2004 * @see java.util.function.BinaryOperator 2005 * @since 1.8 2006 */ 2007 public static long min(long a, long b) { 2008 return Math.min(a, b); 2009 } 2010 2011 /** 2012 * Returns an {@link Optional} containing the nominal descriptor for this 2013 * instance, which is the instance itself. 2014 * 2015 * @return an {@link Optional} describing the {@linkplain Long} instance 2016 * @since 12 2017 */ 2018 @Override 2019 public Optional<Long> describeConstable() { 2020 return Optional.of(this); 2021 } 2022 2023 /** 2024 * Resolves this instance as a {@link ConstantDesc}, the result of which is 2025 * the instance itself. 2026 * 2027 * @param lookup ignored 2028 * @return the {@linkplain Long} instance 2029 * @since 12 2030 */ 2031 @Override 2032 public Long resolveConstantDesc(MethodHandles.Lookup lookup) { 2033 return this; 2034 } 2035 2036 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 2037 @java.io.Serial 2038 @Native private static final long serialVersionUID = 4290774380558885855L; 2039 }