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.AOTSafeClassInitializer;
  41 import jdk.internal.vm.annotation.ForceInline;
  42 import jdk.internal.vm.annotation.IntrinsicCandidate;
  43 import jdk.internal.vm.annotation.Stable;
  44 
  45 import static java.lang.Character.digit;
  46 import static java.lang.String.COMPACT_STRINGS;
  47 
  48 /**
  49  * The {@code Long} class is the {@linkplain
  50  * java.lang##wrapperClass wrapper class} for values of the primitive
  51  * type {@code long}. An object of type {@code Long} contains a
  52  * single field whose type is {@code long}.
  53  *
  54  * <p> In addition, this class provides several methods for converting
  55  * a {@code long} to a {@code String} and a {@code String} to a {@code
  56  * long}, as well as other constants and methods useful when dealing
  57  * with a {@code long}.
  58  *
  59  * <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
  60  * class; programmers should treat instances that are {@linkplain #equals(Object) equal}
  61  * as interchangeable and should not use instances for synchronization, mutexes, or
  62  * with {@linkplain java.lang.ref.Reference object references}.
  63  *
  64  * <div class="preview-block">
  65  *      <div class="preview-comment">
  66  *          When preview features are enabled, {@code Long} is a {@linkplain Class#isValue value class}.
  67  *          Use of value class instances for synchronization, mutexes, or with
  68  *          {@linkplain java.lang.ref.Reference object references} result in
  69  *          {@link IdentityException}.
  70  *      </div>
  71  * </div>
  72  *
  73  *
  74  * <p>Implementation note: The implementations of the "bit twiddling"
  75  * methods (such as {@link #highestOneBit(long) highestOneBit} and
  76  * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are
  77  * based on material from Henry S. Warren, Jr.'s <cite>Hacker's
  78  * Delight</cite>, (Addison Wesley, 2002) and <cite>Hacker's
  79  * Delight, Second Edition</cite>, (Pearson Education, 2013).
  80  *
  81  * @since   1.0
  82  */
  83 @jdk.internal.MigratedValueClass
  84 @jdk.internal.ValueBased
  85 public final class Long extends Number
  86         implements Comparable<Long>, Constable, ConstantDesc {
  87     /**
  88      * A constant holding the minimum value a {@code long} can
  89      * have, -2<sup>63</sup>.
  90      */
  91     @Native public static final long MIN_VALUE = 0x8000000000000000L;
  92 
  93     /**
  94      * A constant holding the maximum value a {@code long} can
  95      * have, 2<sup>63</sup>-1.
  96      */
  97     @Native public static final long MAX_VALUE = 0x7fffffffffffffffL;
  98 
  99     /**
 100      * The {@code Class} instance representing the primitive type
 101      * {@code long}.
 102      *
 103      * @since   1.1
 104      */
 105     public static final Class<Long> TYPE = Class.getPrimitiveClass("long");
 106 
 107     /**
 108      * Returns a string representation of the first argument in the
 109      * radix specified by the second argument.
 110      *
 111      * <p>If the radix is smaller than {@code Character.MIN_RADIX}
 112      * or larger than {@code Character.MAX_RADIX}, then the radix
 113      * {@code 10} is used instead.
 114      *
 115      * <p>If the first argument is negative, the first element of the
 116      * result is the ASCII minus sign {@code '-'}
 117      * ({@code '\u005Cu002d'}). If the first argument is not
 118      * negative, no sign character appears in the result.
 119      *
 120      * <p>The remaining characters of the result represent the magnitude
 121      * of the first argument. If the magnitude is zero, it is
 122      * represented by a single zero character {@code '0'}
 123      * ({@code '\u005Cu0030'}); otherwise, the first character of
 124      * the representation of the magnitude will not be the zero
 125      * character.  The following ASCII characters are used as digits:
 126      *
 127      * <blockquote>
 128      *   {@code 0123456789abcdefghijklmnopqrstuvwxyz}
 129      * </blockquote>
 130      *
 131      * These are {@code '\u005Cu0030'} through
 132      * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through
 133      * {@code '\u005Cu007a'}. If {@code radix} is
 134      * <var>N</var>, then the first <var>N</var> of these characters
 135      * are used as radix-<var>N</var> digits in the order shown. Thus,
 136      * the digits for hexadecimal (radix 16) are
 137      * {@code 0123456789abcdef}. If uppercase letters are
 138      * desired, the {@link java.lang.String#toUpperCase()} method may
 139      * be called on the result:
 140      *
 141      * <blockquote>
 142      *  {@code Long.toString(n, 16).toUpperCase()}
 143      * </blockquote>
 144      *
 145      * @param   i       a {@code long} to be converted to a string.
 146      * @param   radix   the radix to use in the string representation.
 147      * @return  a string representation of the argument in the specified radix.
 148      * @see     java.lang.Character#MAX_RADIX
 149      * @see     java.lang.Character#MIN_RADIX
 150      */
 151     public static String toString(long i, int radix) {
 152         if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
 153             radix = 10;
 154         if (radix == 10)
 155             return toString(i);
 156 
 157         if (COMPACT_STRINGS) {
 158             byte[] buf = new byte[65];
 159             int charPos = 64;
 160             boolean negative = (i < 0);
 161 
 162             if (!negative) {
 163                 i = -i;
 164             }
 165 
 166             while (i <= -radix) {
 167                 buf[charPos--] = Integer.digits[(int)(-(i % radix))];
 168                 i = i / radix;
 169             }
 170             buf[charPos] = Integer.digits[(int)(-i)];
 171 
 172             if (negative) {
 173                 buf[--charPos] = '-';
 174             }
 175             return StringLatin1.newString(buf, charPos, (65 - charPos));
 176         }
 177         return toStringUTF16(i, radix);
 178     }
 179 
 180     private static String toStringUTF16(long i, int radix) {
 181         byte[] buf = new byte[65 * 2];
 182         int charPos = 64;
 183         boolean negative = (i < 0);
 184         if (!negative) {
 185             i = -i;
 186         }
 187         while (i <= -radix) {
 188             StringUTF16.putChar(buf, charPos--, Integer.digits[(int)(-(i % radix))]);
 189             i = i / radix;
 190         }
 191         StringUTF16.putChar(buf, charPos, Integer.digits[(int)(-i)]);
 192         if (negative) {
 193             StringUTF16.putChar(buf, --charPos, '-');
 194         }
 195         return StringUTF16.newString(buf, charPos, (65 - charPos));
 196     }
 197 
 198     /**
 199      * Returns a string representation of the first argument as an
 200      * unsigned integer value in the radix specified by the second
 201      * argument.
 202      *
 203      * <p>If the radix is smaller than {@code Character.MIN_RADIX}
 204      * or larger than {@code Character.MAX_RADIX}, then the radix
 205      * {@code 10} is used instead.
 206      *
 207      * <p>Note that since the first argument is treated as an unsigned
 208      * value, no leading sign character is printed.
 209      *
 210      * <p>If the magnitude is zero, it is represented by a single zero
 211      * character {@code '0'} ({@code '\u005Cu0030'}); otherwise,
 212      * the first character of the representation of the magnitude will
 213      * not be the zero character.
 214      *
 215      * <p>The behavior of radixes and the characters used as digits
 216      * are the same as {@link #toString(long, int) toString}.
 217      *
 218      * @param   i       an integer to be converted to an unsigned string.
 219      * @param   radix   the radix to use in the string representation.
 220      * @return  an unsigned string representation of the argument in the specified radix.
 221      * @see     #toString(long, int)
 222      * @since 1.8
 223      */
 224     public static String toUnsignedString(long i, int radix) {
 225         if (i >= 0)
 226             return toString(i, radix);
 227         else {
 228             return switch (radix) {
 229                 case 2  -> toBinaryString(i);
 230                 case 4  -> toUnsignedString0(i, 2);
 231                 case 8  -> toOctalString(i);
 232                 case 10 -> {
 233                     /*
 234                      * We can get the effect of an unsigned division by 10
 235                      * on a long value by first shifting right, yielding a
 236                      * positive value, and then dividing by 5.  This
 237                      * allows the last digit and preceding digits to be
 238                      * isolated more quickly than by an initial conversion
 239                      * to BigInteger.
 240                      */
 241                     long quot = (i >>> 1) / 5;
 242                     long rem = i - quot * 10;
 243                     yield toString(quot) + rem;
 244                 }
 245                 case 16 -> toHexString(i);
 246                 case 32 -> toUnsignedString0(i, 5);
 247                 default -> toUnsignedBigInteger(i).toString(radix);
 248             };
 249         }
 250     }
 251 
 252     /**
 253      * Return a BigInteger equal to the unsigned value of the
 254      * argument.
 255      */
 256     private static BigInteger toUnsignedBigInteger(long i) {
 257         if (i >= 0L)
 258             return BigInteger.valueOf(i);
 259         else {
 260             int upper = (int) (i >>> 32);
 261             int lower = (int) i;
 262 
 263             // return (upper << 32) + lower
 264             return (BigInteger.valueOf(Integer.toUnsignedLong(upper))).shiftLeft(32).
 265                 add(BigInteger.valueOf(Integer.toUnsignedLong(lower)));
 266         }
 267     }
 268 
 269     /**
 270      * Returns a string representation of the {@code long}
 271      * argument as an unsigned integer in base&nbsp;16.
 272      *
 273      * <p>The unsigned {@code long} value is the argument plus
 274      * 2<sup>64</sup> if the argument is negative; otherwise, it is
 275      * equal to the argument.  This value is converted to a string of
 276      * ASCII digits in hexadecimal (base&nbsp;16) with no extra
 277      * leading {@code 0}s.
 278      *
 279      * <p>The value of the argument can be recovered from the returned
 280      * string {@code s} by calling {@link
 281      * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s,
 282      * 16)}.
 283      *
 284      * <p>If the unsigned magnitude is zero, it is represented by a
 285      * single zero character {@code '0'} ({@code '\u005Cu0030'});
 286      * otherwise, the first character of the representation of the
 287      * unsigned magnitude will not be the zero character. The
 288      * following characters are used as hexadecimal digits:
 289      *
 290      * <blockquote>
 291      *  {@code 0123456789abcdef}
 292      * </blockquote>
 293      *
 294      * These are the characters {@code '\u005Cu0030'} through
 295      * {@code '\u005Cu0039'} and  {@code '\u005Cu0061'} through
 296      * {@code '\u005Cu0066'}.  If uppercase letters are desired,
 297      * the {@link java.lang.String#toUpperCase()} method may be called
 298      * on the result:
 299      *
 300      * <blockquote>
 301      *  {@code Long.toHexString(n).toUpperCase()}
 302      * </blockquote>
 303      *
 304      * @apiNote
 305      * The {@link java.util.HexFormat} class provides formatting and parsing
 306      * of byte arrays and primitives to return a string or adding to an {@link Appendable}.
 307      * {@code HexFormat} formats and parses uppercase or lowercase hexadecimal characters,
 308      * with leading zeros and for byte arrays includes for each byte
 309      * a delimiter, prefix, and suffix.
 310      *
 311      * @param   i   a {@code long} to be converted to a string.
 312      * @return  the string representation of the unsigned {@code long}
 313      *          value represented by the argument in hexadecimal
 314      *          (base&nbsp;16).
 315      * @see java.util.HexFormat
 316      * @see #parseUnsignedLong(String, int)
 317      * @see #toUnsignedString(long, int)
 318      * @since   1.0.2
 319      */
 320     public static String toHexString(long i) {
 321         return toUnsignedString0(i, 4);
 322     }
 323 
 324     /**
 325      * Returns a string representation of the {@code long}
 326      * argument as an unsigned integer in base&nbsp;8.
 327      *
 328      * <p>The unsigned {@code long} value is the argument plus
 329      * 2<sup>64</sup> if the argument is negative; otherwise, it is
 330      * equal to the argument.  This value is converted to a string of
 331      * ASCII digits in octal (base&nbsp;8) with no extra leading
 332      * {@code 0}s.
 333      *
 334      * <p>The value of the argument can be recovered from the returned
 335      * string {@code s} by calling {@link
 336      * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s,
 337      * 8)}.
 338      *
 339      * <p>If the unsigned magnitude is zero, it is represented by a
 340      * single zero character {@code '0'} ({@code '\u005Cu0030'});
 341      * otherwise, the first character of the representation of the
 342      * unsigned magnitude will not be the zero character. The
 343      * following characters are used as octal digits:
 344      *
 345      * <blockquote>
 346      *  {@code 01234567}
 347      * </blockquote>
 348      *
 349      * These are the characters {@code '\u005Cu0030'} through
 350      * {@code '\u005Cu0037'}.
 351      *
 352      * @param   i   a {@code long} to be converted to a string.
 353      * @return  the string representation of the unsigned {@code long}
 354      *          value represented by the argument in octal (base&nbsp;8).
 355      * @see #parseUnsignedLong(String, int)
 356      * @see #toUnsignedString(long, int)
 357      * @since   1.0.2
 358      */
 359     public static String toOctalString(long i) {
 360         return toUnsignedString0(i, 3);
 361     }
 362 
 363     /**
 364      * Returns a string representation of the {@code long}
 365      * argument as an unsigned integer in base&nbsp;2.
 366      *
 367      * <p>The unsigned {@code long} value is the argument plus
 368      * 2<sup>64</sup> if the argument is negative; otherwise, it is
 369      * equal to the argument.  This value is converted to a string of
 370      * ASCII digits in binary (base&nbsp;2) with no extra leading
 371      * {@code 0}s.
 372      *
 373      * <p>The value of the argument can be recovered from the returned
 374      * string {@code s} by calling {@link
 375      * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s,
 376      * 2)}.
 377      *
 378      * <p>If the unsigned magnitude is zero, it is represented by a
 379      * single zero character {@code '0'} ({@code '\u005Cu0030'});
 380      * otherwise, the first character of the representation of the
 381      * unsigned magnitude will not be the zero character. The
 382      * characters {@code '0'} ({@code '\u005Cu0030'}) and {@code
 383      * '1'} ({@code '\u005Cu0031'}) are used as binary digits.
 384      *
 385      * @param   i   a {@code long} to be converted to a string.
 386      * @return  the string representation of the unsigned {@code long}
 387      *          value represented by the argument in binary (base&nbsp;2).
 388      * @see #parseUnsignedLong(String, int)
 389      * @see #toUnsignedString(long, int)
 390      * @since   1.0.2
 391      */
 392     public static String toBinaryString(long i) {
 393         return toUnsignedString0(i, 1);
 394     }
 395 
 396     /**
 397      * Format a long (treated as unsigned) into a String.
 398      * @param val the value to format
 399      * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
 400      */
 401     static String toUnsignedString0(long val, int shift) {
 402         // assert shift > 0 && shift <=5 : "Illegal shift value";
 403         int mag = Long.SIZE - Long.numberOfLeadingZeros(val);
 404         int chars = Math.max(((mag + (shift - 1)) / shift), 1);
 405         byte[] buf = new byte[chars];
 406         formatUnsignedLong0(val, shift, buf, 0, chars);
 407         return String.newStringWithLatin1Bytes(buf);
 408     }
 409 
 410     /**
 411      * Format a long (treated as unsigned) into a byte buffer (LATIN1 version). If
 412      * {@code len} exceeds the formatted ASCII representation of {@code val},
 413      * {@code buf} will be padded with leading zeroes.
 414      *
 415      * @param val the unsigned long to format
 416      * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
 417      * @param buf the byte buffer to write to
 418      * @param offset the offset in the destination buffer to start at
 419      * @param len the number of characters to write
 420      */
 421     private static void formatUnsignedLong0(long val, int shift, byte[] buf, int offset, int len) {
 422         int charPos = offset + len;
 423         int radix = 1 << shift;
 424         int mask = radix - 1;
 425         do {
 426             buf[--charPos] = Integer.digits[((int) val) & mask];
 427             val >>>= shift;
 428         } while (charPos > offset);
 429     }
 430 
 431     /**
 432      * Returns a {@code String} object representing the specified
 433      * {@code long}.  The argument is converted to signed decimal
 434      * representation and returned as a string, exactly as if the
 435      * argument and the radix 10 were given as arguments to the {@link
 436      * #toString(long, int)} method.
 437      *
 438      * @param   i   a {@code long} to be converted.
 439      * @return  a string representation of the argument in base&nbsp;10.
 440      */
 441     public static String toString(long i) {
 442         int size = DecimalDigits.stringSize(i);
 443         byte[] buf = new byte[size];
 444         DecimalDigits.uncheckedGetCharsLatin1(i, size, buf);
 445         return String.newStringWithLatin1Bytes(buf);
 446     }
 447 
 448     /**
 449      * Returns a string representation of the argument as an unsigned
 450      * decimal value.
 451      *
 452      * The argument is converted to unsigned decimal representation
 453      * and returned as a string exactly as if the argument and radix
 454      * 10 were given as arguments to the {@link #toUnsignedString(long,
 455      * int)} method.
 456      *
 457      * @param   i  an integer to be converted to an unsigned string.
 458      * @return  an unsigned string representation of the argument.
 459      * @see     #toUnsignedString(long, int)
 460      * @since 1.8
 461      */
 462     public static String toUnsignedString(long i) {
 463         return toUnsignedString(i, 10);
 464     }
 465 
 466     /**
 467      * Parses the string argument as a signed {@code long} in the
 468      * radix specified by the second argument. The characters in the
 469      * string must all be digits of the specified radix (as determined
 470      * by whether {@link java.lang.Character#digit(char, int)} returns
 471      * a nonnegative value), except that the first character may be an
 472      * ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to
 473      * indicate a negative value or an ASCII plus sign {@code '+'}
 474      * ({@code '\u005Cu002B'}) to indicate a positive value. The
 475      * resulting {@code long} value is returned.
 476      *
 477      * <p>Note that neither the character {@code L}
 478      * ({@code '\u005Cu004C'}) nor {@code l}
 479      * ({@code '\u005Cu006C'}) is permitted to appear at the end
 480      * of the string as a type indicator, as would be permitted in
 481      * Java programming language source code - except that either
 482      * {@code L} or {@code l} may appear as a digit for a
 483      * radix greater than or equal to 22.
 484      *
 485      * <p>An exception of type {@code NumberFormatException} is
 486      * thrown if any of the following situations occurs:
 487      * <ul>
 488      *
 489      * <li>The first argument is {@code null} or is a string of
 490      * length zero.
 491      *
 492      * <li>The {@code radix} is either smaller than {@link
 493      * java.lang.Character#MIN_RADIX} or larger than {@link
 494      * java.lang.Character#MAX_RADIX}.
 495      *
 496      * <li>Any character of the string is not a digit of the specified
 497      * radix, except that the first character may be a minus sign
 498      * {@code '-'} ({@code '\u005Cu002d'}) or plus sign {@code
 499      * '+'} ({@code '\u005Cu002B'}) provided that the string is
 500      * longer than length 1.
 501      *
 502      * <li>The value represented by the string is not a value of type
 503      *      {@code long}.
 504      * </ul>
 505      *
 506      * <p>Examples:
 507      * <blockquote><pre>
 508      * parseLong("0", 10) returns 0L
 509      * parseLong("473", 10) returns 473L
 510      * parseLong("+42", 10) returns 42L
 511      * parseLong("-0", 10) returns 0L
 512      * parseLong("-FF", 16) returns -255L
 513      * parseLong("1100110", 2) returns 102L
 514      * parseLong("99", 8) throws a NumberFormatException
 515      * parseLong("Hazelnut", 10) throws a NumberFormatException
 516      * parseLong("Hazelnut", 36) returns 1356099454469L
 517      * </pre></blockquote>
 518      *
 519      * @param      s       the {@code String} containing the
 520      *                     {@code long} representation to be parsed.
 521      * @param      radix   the radix to be used while parsing {@code s}.
 522      * @return     the {@code long} represented by the string argument in
 523      *             the specified radix.
 524      * @throws     NumberFormatException  if the string does not contain a
 525      *             parsable {@code long}.
 526      */
 527     public static long parseLong(String s, int radix)
 528                 throws NumberFormatException {
 529         if (s == null) {
 530             throw new NumberFormatException("Cannot parse null string");
 531         }
 532 
 533         if (radix < Character.MIN_RADIX) {
 534             throw new NumberFormatException(String.format(
 535                 "radix %s less than Character.MIN_RADIX", radix));
 536         }
 537 
 538         if (radix > Character.MAX_RADIX) {
 539             throw new NumberFormatException(String.format(
 540                 "radix %s greater than Character.MAX_RADIX", radix));
 541         }
 542 
 543         int len = s.length();
 544         if (len == 0) {
 545             throw NumberFormatException.forInputString("", radix);
 546         }
 547         int digit = ~0xFF;
 548         int i = 0;
 549         char firstChar = s.charAt(i++);
 550         if (firstChar != '-' && firstChar != '+') {
 551             digit = digit(firstChar, radix);
 552         }
 553         if (digit >= 0 || digit == ~0xFF && len > 1) {
 554             long limit = firstChar != '-' ? MIN_VALUE + 1 : MIN_VALUE;
 555             long multmin = limit / radix;
 556             long result = -(digit & 0xFF);
 557             boolean inRange = true;
 558             /* Accumulating negatively avoids surprises near MAX_VALUE */
 559             while (i < len && (digit = digit(s.charAt(i++), radix)) >= 0
 560                     && (inRange = result > multmin
 561                         || result == multmin && digit <= (int) (radix * multmin - limit))) {
 562                 result = radix * result - digit;
 563             }
 564             if (inRange && i == len && digit >= 0) {
 565                 return firstChar != '-' ? -result : result;
 566             }
 567         }
 568         throw NumberFormatException.forInputString(s, radix);
 569     }
 570 
 571     /**
 572      * Parses the {@link CharSequence} argument as a signed {@code long} in
 573      * the specified {@code radix}, beginning at the specified
 574      * {@code beginIndex} and extending to {@code endIndex - 1}.
 575      *
 576      * <p>The method does not take steps to guard against the
 577      * {@code CharSequence} being mutated while parsing.
 578      *
 579      * @param      s   the {@code CharSequence} containing the {@code long}
 580      *                  representation to be parsed
 581      * @param      beginIndex   the beginning index, inclusive.
 582      * @param      endIndex     the ending index, exclusive.
 583      * @param      radix   the radix to be used while parsing {@code s}.
 584      * @return     the signed {@code long} represented by the subsequence in
 585      *             the specified radix.
 586      * @throws     NullPointerException  if {@code s} is null.
 587      * @throws     IndexOutOfBoundsException  if {@code beginIndex} is
 588      *             negative, or if {@code beginIndex} is greater than
 589      *             {@code endIndex} or if {@code endIndex} is greater than
 590      *             {@code s.length()}.
 591      * @throws     NumberFormatException  if the {@code CharSequence} does not
 592      *             contain a parsable {@code long} in the specified
 593      *             {@code radix}, or if {@code radix} is either smaller than
 594      *             {@link java.lang.Character#MIN_RADIX} or larger than
 595      *             {@link java.lang.Character#MAX_RADIX}.
 596      * @since  9
 597      */
 598     public static long parseLong(CharSequence s, int beginIndex, int endIndex, int radix)
 599                 throws NumberFormatException {
 600         Objects.requireNonNull(s);
 601         Objects.checkFromToIndex(beginIndex, endIndex, s.length());
 602 
 603         if (radix < Character.MIN_RADIX) {
 604             throw new NumberFormatException(String.format(
 605                 "radix %s less than Character.MIN_RADIX", radix));
 606         }
 607 
 608         if (radix > Character.MAX_RADIX) {
 609             throw new NumberFormatException(String.format(
 610                 "radix %s greater than Character.MAX_RADIX", radix));
 611         }
 612 
 613         /*
 614          * While s can be concurrently modified, it is ensured that each
 615          * of its characters is read at most once, from lower to higher indices.
 616          * This is obtained by reading them using the pattern s.charAt(i++),
 617          * and by not updating i anywhere else.
 618          */
 619         if (beginIndex == endIndex) {
 620             throw NumberFormatException.forInputString("", radix);
 621         }
 622         int digit = ~0xFF;  // ~0xFF means firstChar char is sign
 623         int i = beginIndex;
 624         char firstChar = s.charAt(i++);
 625         if (firstChar != '-' && firstChar != '+') {
 626             digit = digit(firstChar, radix);
 627         }
 628         if (digit >= 0 || digit == ~0xFF && endIndex - beginIndex > 1) {
 629             long limit = firstChar != '-' ? MIN_VALUE + 1 : MIN_VALUE;
 630             long multmin = limit / radix;
 631             long result = -(digit & 0xFF);
 632             boolean inRange = true;
 633             /* Accumulating negatively avoids surprises near MAX_VALUE */
 634             while (i < endIndex && (digit = digit(s.charAt(i++), radix)) >= 0
 635                     && (inRange = result > multmin
 636                         || result == multmin && digit <= (int) (radix * multmin - limit))) {
 637                 result = radix * result - digit;
 638             }
 639             if (inRange && i == endIndex && digit >= 0) {
 640                 return firstChar != '-' ? -result : result;
 641             }
 642         }
 643         throw NumberFormatException.forCharSequence(s, beginIndex,
 644             endIndex, i - (digit < -1 ? 0 : 1));
 645     }
 646 
 647     /**
 648      * Parses the string argument as a signed decimal {@code long}.
 649      * The characters in the string must all be decimal digits, except
 650      * that the first character may be an ASCII minus sign {@code '-'}
 651      * ({@code \u005Cu002D'}) to indicate a negative value or an
 652      * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
 653      * indicate a positive value. The resulting {@code long} value is
 654      * returned, exactly as if the argument and the radix {@code 10}
 655      * were given as arguments to the {@link
 656      * #parseLong(java.lang.String, int)} method.
 657      *
 658      * <p>Note that neither the character {@code L}
 659      * ({@code '\u005Cu004C'}) nor {@code l}
 660      * ({@code '\u005Cu006C'}) is permitted to appear at the end
 661      * of the string as a type indicator, as would be permitted in
 662      * Java programming language source code.
 663      *
 664      * @param      s   a {@code String} containing the {@code long}
 665      *             representation to be parsed
 666      * @return     the {@code long} represented by the argument in
 667      *             decimal.
 668      * @throws     NumberFormatException  if the string does not contain a
 669      *             parsable {@code long}.
 670      */
 671     public static long parseLong(String s) throws NumberFormatException {
 672         return parseLong(s, 10);
 673     }
 674 
 675     /**
 676      * Parses the string argument as an unsigned {@code long} in the
 677      * radix specified by the second argument.  An unsigned integer
 678      * maps the values usually associated with negative numbers to
 679      * positive numbers larger than {@code MAX_VALUE}.
 680      *
 681      * The characters in the string must all be digits of the
 682      * specified radix (as determined by whether {@link
 683      * java.lang.Character#digit(char, int)} returns a nonnegative
 684      * value), except that the first character may be an ASCII plus
 685      * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting
 686      * integer value is returned.
 687      *
 688      * <p>An exception of type {@code NumberFormatException} is
 689      * thrown if any of the following situations occurs:
 690      * <ul>
 691      * <li>The first argument is {@code null} or is a string of
 692      * length zero.
 693      *
 694      * <li>The radix is either smaller than
 695      * {@link java.lang.Character#MIN_RADIX} or
 696      * larger than {@link java.lang.Character#MAX_RADIX}.
 697      *
 698      * <li>Any character of the string is not a digit of the specified
 699      * radix, except that the first character may be a plus sign
 700      * {@code '+'} ({@code '\u005Cu002B'}) provided that the
 701      * string is longer than length 1.
 702      *
 703      * <li>The value represented by the string is larger than the
 704      * largest unsigned {@code long}, 2<sup>64</sup>-1.
 705      *
 706      * </ul>
 707      *
 708      *
 709      * @param      s   the {@code String} containing the unsigned integer
 710      *                  representation to be parsed
 711      * @param      radix   the radix to be used while parsing {@code s}.
 712      * @return     the unsigned {@code long} represented by the string
 713      *             argument in the specified radix.
 714      * @throws     NumberFormatException if the {@code String}
 715      *             does not contain a parsable {@code long}.
 716      * @since 1.8
 717      */
 718     public static long parseUnsignedLong(String s, int radix)
 719                 throws NumberFormatException {
 720         if (s == null)  {
 721             throw new NumberFormatException("Cannot parse null string");
 722         }
 723 
 724         if (radix < Character.MIN_RADIX) {
 725             throw new NumberFormatException(String.format(
 726                 "radix %s less than Character.MIN_RADIX", radix));
 727         }
 728 
 729         if (radix > Character.MAX_RADIX) {
 730             throw new NumberFormatException(String.format(
 731                 "radix %s greater than Character.MAX_RADIX", radix));
 732         }
 733 
 734         int len = s.length();
 735         if (len == 0) {
 736             throw NumberFormatException.forInputString(s, radix);
 737         }
 738         int i = 0;
 739         char firstChar = s.charAt(i++);
 740         if (firstChar == '-') {
 741             throw new NumberFormatException(String.format(
 742                 "Illegal leading minus sign on unsigned string %s.", s));
 743         }
 744         int digit = ~0xFF;
 745         if (firstChar != '+') {
 746             digit = digit(firstChar, radix);
 747         }
 748         if (digit >= 0 || digit == ~0xFF && len > 1) {
 749             long multmax = divideUnsigned(-1L, radix);  // -1L is max unsigned long
 750             long result = digit & 0xFF;
 751             boolean inRange = true;
 752             while (i < len && (digit = digit(s.charAt(i++), radix)) >= 0
 753                     && (inRange = compareUnsigned(result, multmax) < 0
 754                         || result == multmax && digit < (int) (-radix * multmax))) {
 755                 result = radix * result + digit;
 756             }
 757             if (inRange && i == len && digit >= 0) {
 758                 return result;
 759             }
 760         }
 761         if (digit < 0) {
 762             throw NumberFormatException.forInputString(s, radix);
 763         }
 764         throw new NumberFormatException(String.format(
 765             "String value %s exceeds range of unsigned long.", s));
 766     }
 767 
 768     /**
 769      * Parses the {@link CharSequence} argument as an unsigned {@code long} in
 770      * the specified {@code radix}, beginning at the specified
 771      * {@code beginIndex} and extending to {@code endIndex - 1}.
 772      *
 773      * <p>The method does not take steps to guard against the
 774      * {@code CharSequence} being mutated while parsing.
 775      *
 776      * @param      s   the {@code CharSequence} containing the unsigned
 777      *                 {@code long} representation to be parsed
 778      * @param      beginIndex   the beginning index, inclusive.
 779      * @param      endIndex     the ending index, exclusive.
 780      * @param      radix   the radix to be used while parsing {@code s}.
 781      * @return     the unsigned {@code long} represented by the subsequence in
 782      *             the specified radix.
 783      * @throws     NullPointerException  if {@code s} is null.
 784      * @throws     IndexOutOfBoundsException  if {@code beginIndex} is
 785      *             negative, or if {@code beginIndex} is greater than
 786      *             {@code endIndex} or if {@code endIndex} is greater than
 787      *             {@code s.length()}.
 788      * @throws     NumberFormatException  if the {@code CharSequence} does not
 789      *             contain a parsable unsigned {@code long} in the specified
 790      *             {@code radix}, or if {@code radix} is either smaller than
 791      *             {@link java.lang.Character#MIN_RADIX} or larger than
 792      *             {@link java.lang.Character#MAX_RADIX}.
 793      * @since  9
 794      */
 795     public static long parseUnsignedLong(CharSequence s, int beginIndex, int endIndex, int radix)
 796                 throws NumberFormatException {
 797         Objects.requireNonNull(s);
 798         Objects.checkFromToIndex(beginIndex, endIndex, s.length());
 799 
 800         if (radix < Character.MIN_RADIX) {
 801             throw new NumberFormatException(String.format(
 802                 "radix %s less than Character.MIN_RADIX", radix));
 803         }
 804 
 805         if (radix > Character.MAX_RADIX) {
 806             throw new NumberFormatException(String.format(
 807                 "radix %s greater than Character.MAX_RADIX", radix));
 808         }
 809 
 810         /*
 811          * While s can be concurrently modified, it is ensured that each
 812          * of its characters is read at most once, from lower to higher indices.
 813          * This is obtained by reading them using the pattern s.charAt(i++),
 814          * and by not updating i anywhere else.
 815          */
 816         if (beginIndex == endIndex) {
 817             throw NumberFormatException.forInputString("", radix);
 818         }
 819         int i = beginIndex;
 820         char firstChar = s.charAt(i++);
 821         if (firstChar == '-') {
 822             throw new NumberFormatException(
 823                 "Illegal leading minus sign on unsigned string " + s + ".");
 824         }
 825         int digit = ~0xFF;
 826         if (firstChar != '+') {
 827             digit = digit(firstChar, radix);
 828         }
 829         if (digit >= 0 || digit == ~0xFF && endIndex - beginIndex > 1) {
 830             long multmax = divideUnsigned(-1L, radix);  // -1L is max unsigned long
 831             long result = digit & 0xFF;
 832             boolean inRange = true;
 833             while (i < endIndex && (digit = digit(s.charAt(i++), radix)) >= 0
 834                     && (inRange = compareUnsigned(result, multmax) < 0
 835                         || result == multmax && digit < (int) (-radix * multmax))) {
 836                 result = radix * result + digit;
 837             }
 838             if (inRange && i == endIndex && digit >= 0) {
 839                 return result;
 840             }
 841         }
 842         if (digit < 0) {
 843             throw NumberFormatException.forCharSequence(s, beginIndex,
 844                 endIndex, i - (digit < -1 ? 0 : 1));
 845         }
 846         throw new NumberFormatException(String.format(
 847             "String value %s exceeds range of unsigned long.", s));
 848     }
 849 
 850     /**
 851      * Parses the string argument as an unsigned decimal {@code long}. The
 852      * characters in the string must all be decimal digits, except
 853      * that the first character may be an ASCII plus sign {@code
 854      * '+'} ({@code '\u005Cu002B'}). The resulting integer value
 855      * is returned, exactly as if the argument and the radix 10 were
 856      * given as arguments to the {@link
 857      * #parseUnsignedLong(java.lang.String, int)} method.
 858      *
 859      * @param s   a {@code String} containing the unsigned {@code long}
 860      *            representation to be parsed
 861      * @return    the unsigned {@code long} value represented by the decimal string argument
 862      * @throws    NumberFormatException  if the string does not contain a
 863      *            parsable unsigned integer.
 864      * @since 1.8
 865      */
 866     public static long parseUnsignedLong(String s) throws NumberFormatException {
 867         return parseUnsignedLong(s, 10);
 868     }
 869 
 870     /**
 871      * Returns a {@code Long} object holding the value
 872      * extracted from the specified {@code String} when parsed
 873      * with the radix given by the second argument.  The first
 874      * argument is interpreted as representing a signed
 875      * {@code long} in the radix specified by the second
 876      * argument, exactly as if the arguments were given to the {@link
 877      * #parseLong(java.lang.String, int)} method. The result is a
 878      * {@code Long} object that represents the {@code long}
 879      * value specified by the string.
 880      *
 881      * <p>In other words, this method returns a {@code Long} object equal
 882      * to the value of:
 883      *
 884      * <blockquote>
 885      *  {@code Long.valueOf(Long.parseLong(s, radix))}
 886      * </blockquote>
 887      *
 888      * @param      s       the string to be parsed
 889      * @param      radix   the radix to be used in interpreting {@code s}
 890      * @return     a {@code Long} object holding the value
 891      *             represented by the string argument in the specified
 892      *             radix.
 893      * @throws     NumberFormatException  If the {@code String} does not
 894      *             contain a parsable {@code long}.
 895      */
 896     public static Long valueOf(String s, int radix) throws NumberFormatException {
 897         return Long.valueOf(parseLong(s, radix));
 898     }
 899 
 900     /**
 901      * Returns a {@code Long} object holding the value
 902      * of the specified {@code String}. The argument is
 903      * interpreted as representing a signed decimal {@code long},
 904      * exactly as if the argument were given to the {@link
 905      * #parseLong(java.lang.String)} method. The result is a
 906      * {@code Long} object that represents the integer value
 907      * specified by the string.
 908      *
 909      * <p>In other words, this method returns a {@code Long} object
 910      * equal to the value of:
 911      *
 912      * <blockquote>
 913      *  {@code Long.valueOf(Long.parseLong(s))}
 914      * </blockquote>
 915      *
 916      * @param      s   the string to be parsed.
 917      * @return     a {@code Long} object holding the value
 918      *             represented by the string argument.
 919      * @throws     NumberFormatException  If the string cannot be parsed
 920      *             as a {@code long}.
 921      */
 922     public static Long valueOf(String s) throws NumberFormatException
 923     {
 924         return Long.valueOf(parseLong(s, 10));
 925     }
 926 
 927     @AOTSafeClassInitializer
 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 }