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