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