1 /*
   2  * Copyright (c) 1994, 2026, 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             if (!PreviewFeatures.isEnabled()) {
 937                 int size = -(-128) + 127 + 1;
 938 
 939                 // Load and use the archived cache if it exists
 940                 CDS.initializeFromArchive(LongCache.class);
 941                 if (archivedCache == null) {
 942                     Long[] c = new Long[size];
 943                     long value = -128;
 944                     for(int i = 0; i < size; i++) {
 945                         c[i] = new Long(value++);
 946                     }
 947                     archivedCache = c;
 948                 }
 949                 cache = archivedCache;
 950                 assert cache.length == size;
 951             } else {
 952                 cache = null;
 953                 assert archivedCache == null;
 954             }
 955         }
 956     }
 957 
 958     /**
 959      * Returns a {@code Long} instance representing the specified
 960      * {@code long} value.
 961      * <div class="preview-block">
 962      *      <div class="preview-comment">
 963      *          <p>
 964      *              - When preview features are NOT enabled, {@code Long} is an identity class.
 965      *              If a new {@code Long} instance is not required, this method
 966      *              should generally be used in preference to the constructor
 967      *              {@link #Long(long)}, as this method is likely to yield
 968      *              significantly better space and time performance by caching
 969      *              frequently requested values.
 970      *              This method will always cache values in the range -128 to 127,
 971      *              inclusive, and may cache other values outside of this range.
 972      *          </p>
 973      *          <p>
 974      *              - When preview features are enabled, {@code Long} is a {@linkplain Class#isValue value class}.
 975      *              The {@code valueOf} behavior is the same as invoking the constructor,
 976      *              whether cached or not.
 977      *          </p>
 978      *      </div>
 979      * </div>
 980      *
 981      * @param  l a long value.
 982      * @return a {@code Long} instance representing {@code l}.
 983      * @since  1.5
 984      */
 985     @IntrinsicCandidate
 986     @DeserializeConstructor
 987     public static Long valueOf(long l) {
 988         if (!PreviewFeatures.isEnabled()) {
 989             if (l >= -128 && l <= 127) { // will cache
 990                 final int offset = 128;
 991                 return LongCache.cache[(int) l + offset];
 992             }
 993         }
 994         return new Long(l);
 995     }
 996 
 997     /**
 998      * Decodes a {@code String} into a {@code Long}.
 999      * Accepts decimal, hexadecimal, and octal numbers given by the
1000      * following grammar:
1001      *
1002      * <blockquote>
1003      * <dl>
1004      * <dt><i>DecodableString:</i>
1005      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
1006      * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
1007      * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
1008      * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
1009      * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
1010      *
1011      * <dt><i>Sign:</i>
1012      * <dd>{@code -}
1013      * <dd>{@code +}
1014      * </dl>
1015      * </blockquote>
1016      *
1017      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
1018      * are as defined in section {@jls 3.10.1} of
1019      * <cite>The Java Language Specification</cite>,
1020      * except that underscores are not accepted between digits.
1021      *
1022      * <p>The sequence of characters following an optional
1023      * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
1024      * "{@code #}", or leading zero) is parsed as by the {@code
1025      * Long.parseLong} method with the indicated radix (10, 16, or 8).
1026      * This sequence of characters must represent a positive value or
1027      * a {@link NumberFormatException} will be thrown.  The result is
1028      * negated if first character of the specified {@code String} is
1029      * the minus sign.  No whitespace characters are permitted in the
1030      * {@code String}.
1031      *
1032      * @param     nm the {@code String} to decode.
1033      * @return    a {@code Long} object holding the {@code long}
1034      *            value represented by {@code nm}
1035      * @throws    NumberFormatException  if the {@code String} does not
1036      *            contain a parsable {@code long}.
1037      * @see java.lang.Long#parseLong(String, int)
1038      * @since 1.2
1039      */
1040     public static Long decode(String nm) throws NumberFormatException {
1041         int radix = 10;
1042         int index = 0;
1043         boolean negative = false;
1044         long result;
1045 
1046         if (nm.isEmpty())
1047             throw new NumberFormatException("Zero length string");
1048         char firstChar = nm.charAt(0);
1049         // Handle sign, if present
1050         if (firstChar == '-') {
1051             negative = true;
1052             index++;
1053         } else if (firstChar == '+')
1054             index++;
1055 
1056         // Handle radix specifier, if present
1057         if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
1058             index += 2;
1059             radix = 16;
1060         }
1061         else if (nm.startsWith("#", index)) {
1062             index ++;
1063             radix = 16;
1064         }
1065         else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
1066             index ++;
1067             radix = 8;
1068         }
1069 
1070         if (nm.startsWith("-", index) || nm.startsWith("+", index))
1071             throw new NumberFormatException("Sign character in wrong position");
1072 
1073         try {
1074             result = parseLong(nm, index, nm.length(), radix);
1075             result = negative ? -result : result;
1076         } catch (NumberFormatException e) {
1077             // If number is Long.MIN_VALUE, we'll end up here. The next line
1078             // handles this case, and causes any genuine format error to be
1079             // rethrown.
1080             String constant = negative ? ("-" + nm.substring(index))
1081                                        : nm.substring(index);
1082             result = parseLong(constant, radix);
1083         }
1084         return result;
1085     }
1086 
1087     /**
1088      * The value of the {@code Long}.
1089      *
1090      * @serial
1091      */
1092     private final long value;
1093 
1094     /**
1095      * Constructs a newly allocated {@code Long} object that
1096      * represents the specified {@code long} argument.
1097      *
1098      * @param   value   the value to be represented by the
1099      *          {@code Long} object.
1100      *
1101      * @deprecated
1102      * It is rarely appropriate to use this constructor. The static factory
1103      * {@link #valueOf(long)} is generally a better choice, as it is
1104      * likely to yield significantly better space and time performance.
1105      */
1106     @Deprecated(since="9")
1107     public Long(long value) {
1108         this.value = value;
1109     }
1110 
1111     /**
1112      * Constructs a newly allocated {@code Long} object that
1113      * represents the {@code long} value indicated by the
1114      * {@code String} parameter. The string is converted to a
1115      * {@code long} value in exactly the manner used by the
1116      * {@code parseLong} method for radix 10.
1117      *
1118      * @param      s   the {@code String} to be converted to a
1119      *             {@code Long}.
1120      * @throws     NumberFormatException  if the {@code String} does not
1121      *             contain a parsable {@code long}.
1122      *
1123      * @deprecated
1124      * It is rarely appropriate to use this constructor.
1125      * Use {@link #parseLong(String)} to convert a string to a
1126      * {@code long} primitive, or use {@link #valueOf(String)}
1127      * to convert a string to a {@code Long} object.
1128      */
1129     @Deprecated(since="9")
1130     public Long(String s) throws NumberFormatException {
1131         this.value = parseLong(s, 10);
1132     }
1133 
1134     /**
1135      * Returns the value of this {@code Long} as a {@code byte} after
1136      * a narrowing primitive conversion.
1137      * @jls 5.1.3 Narrowing Primitive Conversion
1138      */
1139     public byte byteValue() {
1140         return (byte)value;
1141     }
1142 
1143     /**
1144      * Returns the value of this {@code Long} as a {@code short} after
1145      * a narrowing primitive conversion.
1146      * @jls 5.1.3 Narrowing Primitive Conversion
1147      */
1148     public short shortValue() {
1149         return (short)value;
1150     }
1151 
1152     /**
1153      * Returns the value of this {@code Long} as an {@code int} after
1154      * a narrowing primitive conversion.
1155      * @jls 5.1.3 Narrowing Primitive Conversion
1156      */
1157     public int intValue() {
1158         return (int)value;
1159     }
1160 
1161     /**
1162      * Returns the value of this {@code Long} as a
1163      * {@code long} value.
1164      */
1165     @IntrinsicCandidate
1166     public long longValue() {
1167         return value;
1168     }
1169 
1170     /**
1171      * Returns the value of this {@code Long} as a {@code float} after
1172      * a widening primitive conversion.
1173      * @jls 5.1.2 Widening Primitive Conversion
1174      */
1175     public float floatValue() {
1176         return (float)value;
1177     }
1178 
1179     /**
1180      * Returns the value of this {@code Long} as a {@code double}
1181      * after a widening primitive conversion.
1182      * @jls 5.1.2 Widening Primitive Conversion
1183      */
1184     public double doubleValue() {
1185         return (double)value;
1186     }
1187 
1188     /**
1189      * Returns a {@code String} object representing this
1190      * {@code Long}'s value.  The value is converted to signed
1191      * decimal representation and returned as a string, exactly as if
1192      * the {@code long} value were given as an argument to the
1193      * {@link java.lang.Long#toString(long)} method.
1194      *
1195      * @return  a string representation of the value of this object in
1196      *          base&nbsp;10.
1197      */
1198     public String toString() {
1199         return toString(value);
1200     }
1201 
1202     /**
1203      * Returns a hash code for this {@code Long}. The result is
1204      * the exclusive OR of the two halves of the primitive
1205      * {@code long} value held by this {@code Long}
1206      * object. That is, the hashcode is the value of the expression:
1207      *
1208      * <blockquote>
1209      *  {@code (int)(this.longValue()^(this.longValue()>>>32))}
1210      * </blockquote>
1211      *
1212      * @return  a hash code value for this object.
1213      */
1214     @Override
1215     public int hashCode() {
1216         return Long.hashCode(value);
1217     }
1218 
1219     /**
1220      * Returns a hash code for a {@code long} value; compatible with
1221      * {@code Long.hashCode()}.
1222      *
1223      * @param value the value to hash
1224      * @return a hash code value for a {@code long} value.
1225      * @since 1.8
1226      */
1227     public static int hashCode(long value) {
1228         return (int)(value ^ (value >>> 32));
1229     }
1230 
1231     /**
1232      * Compares this object to the specified object.  The result is
1233      * {@code true} if and only if the argument is not
1234      * {@code null} and is a {@code Long} object that
1235      * contains the same {@code long} value as this object.
1236      *
1237      * @param   obj   the object to compare with.
1238      * @return  {@code true} if the objects are the same;
1239      *          {@code false} otherwise.
1240      */
1241     public boolean equals(Object obj) {
1242         if (obj instanceof Long ell) {
1243             return value == ell.longValue();
1244         }
1245         return false;
1246     }
1247 
1248     /**
1249      * Determines the {@code long} value of the system property
1250      * with the specified name.
1251      *
1252      * <p>The first argument is treated as the name of a system
1253      * property.  System properties are accessible through the {@link
1254      * java.lang.System#getProperty(java.lang.String)} method. The
1255      * string value of this property is then interpreted as a {@code
1256      * long} value using the grammar supported by {@link Long#decode decode}
1257      * and a {@code Long} object representing this value is returned.
1258      *
1259      * <p>If there is no property with the specified name, if the
1260      * specified name is empty or {@code null}, or if the property
1261      * does not have the correct numeric format, then {@code null} is
1262      * returned.
1263      *
1264      * <p>In other words, this method returns a {@code Long} object
1265      * equal to the value of:
1266      *
1267      * <blockquote>
1268      *  {@code getLong(nm, null)}
1269      * </blockquote>
1270      *
1271      * @param   nm   property name.
1272      * @return  the {@code Long} value of the property.
1273      * @see     java.lang.System#getProperty(java.lang.String)
1274      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
1275      */
1276     public static Long getLong(String nm) {
1277         return getLong(nm, null);
1278     }
1279 
1280     /**
1281      * Determines the {@code long} value of the system property
1282      * with the specified name.
1283      *
1284      * <p>The first argument is treated as the name of a system
1285      * property.  System properties are accessible through the {@link
1286      * java.lang.System#getProperty(java.lang.String)} method. The
1287      * string value of this property is then interpreted as a {@code
1288      * long} value using the grammar supported by {@link Long#decode decode}
1289      * and a {@code Long} object representing this value is returned.
1290      *
1291      * <p>The second argument is the default value. A {@code Long} object
1292      * that represents the value of the second argument is returned if there
1293      * is no property of the specified name, if the property does not have
1294      * the correct numeric format, or if the specified name is empty or null.
1295      *
1296      * <p>In other words, this method returns a {@code Long} object equal
1297      * to the value of:
1298      *
1299      * <blockquote>
1300      *  {@code getLong(nm, Long.valueOf(val))}
1301      * </blockquote>
1302      *
1303      * but in practice it may be implemented in a manner such as:
1304      *
1305      * <blockquote><pre>
1306      * Long result = getLong(nm, null);
1307      * return (result == null) ? Long.valueOf(val) : result;
1308      * </pre></blockquote>
1309      *
1310      * to avoid the unnecessary allocation of a {@code Long} object when
1311      * the default value is not needed.
1312      *
1313      * @param   nm    property name.
1314      * @param   val   default value.
1315      * @return  the {@code Long} value of the property.
1316      * @see     java.lang.System#getProperty(java.lang.String)
1317      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
1318      */
1319     public static Long getLong(String nm, long val) {
1320         Long result = Long.getLong(nm, null);
1321         return (result == null) ? Long.valueOf(val) : result;
1322     }
1323 
1324     /**
1325      * Returns the {@code long} value of the system property with
1326      * the specified name.  The first argument is treated as the name
1327      * of a system property.  System properties are accessible through
1328      * the {@link java.lang.System#getProperty(java.lang.String)}
1329      * method. The string value of this property is then interpreted
1330      * as a {@code long} value, as per the
1331      * {@link Long#decode decode} method, and a {@code Long} object
1332      * representing this value is returned; in summary:
1333      *
1334      * <ul>
1335      * <li>If the property value begins with the two ASCII characters
1336      * {@code 0x} or the ASCII character {@code #}, not followed by
1337      * a minus sign, then the rest of it is parsed as a hexadecimal integer
1338      * exactly as for the method {@link #valueOf(java.lang.String, int)}
1339      * with radix 16.
1340      * <li>If the property value begins with the ASCII character
1341      * {@code 0} followed by another character, it is parsed as
1342      * an octal integer exactly as by the method {@link
1343      * #valueOf(java.lang.String, int)} with radix 8.
1344      * <li>Otherwise the property value is parsed as a decimal
1345      * integer exactly as by the method
1346      * {@link #valueOf(java.lang.String, int)} with radix 10.
1347      * </ul>
1348      *
1349      * <p>Note that, in every case, neither {@code L}
1350      * ({@code '\u005Cu004C'}) nor {@code l}
1351      * ({@code '\u005Cu006C'}) is permitted to appear at the end
1352      * of the property value as a type indicator, as would be
1353      * permitted in Java programming language source code.
1354      *
1355      * <p>The second argument is the default value. The default value is
1356      * returned if there is no property of the specified name, if the
1357      * property does not have the correct numeric format, or if the
1358      * specified name is empty or {@code null}.
1359      *
1360      * @param   nm   property name.
1361      * @param   val   default value.
1362      * @return  the {@code Long} value of the property.
1363      * @see     System#getProperty(java.lang.String)
1364      * @see     System#getProperty(java.lang.String, java.lang.String)
1365      */
1366     public static Long getLong(String nm, Long val) {
1367         String v = nm != null && !nm.isEmpty() ? System.getProperty(nm) : null;
1368         if (v != null) {
1369             try {
1370                 return Long.decode(v);
1371             } catch (NumberFormatException e) {
1372             }
1373         }
1374         return val;
1375     }
1376 
1377     /**
1378      * Compares two {@code Long} objects numerically.
1379      *
1380      * @param   anotherLong   the {@code Long} to be compared.
1381      * @return  the value {@code 0} if this {@code Long} is
1382      *          equal to the argument {@code Long}; a value less than
1383      *          {@code 0} if this {@code Long} is numerically less
1384      *          than the argument {@code Long}; and a value greater
1385      *          than {@code 0} if this {@code Long} is numerically
1386      *           greater than the argument {@code Long} (signed
1387      *           comparison).
1388      * @since   1.2
1389      */
1390     public int compareTo(Long anotherLong) {
1391         return compare(this.value, anotherLong.value);
1392     }
1393 
1394     /**
1395      * Compares two {@code long} values numerically.
1396      * The value returned is identical to what would be returned by:
1397      * <pre>
1398      *    Long.valueOf(x).compareTo(Long.valueOf(y))
1399      * </pre>
1400      *
1401      * @param  x the first {@code long} to compare
1402      * @param  y the second {@code long} to compare
1403      * @return the value {@code 0} if {@code x == y};
1404      *         a value less than {@code 0} if {@code x < y}; and
1405      *         a value greater than {@code 0} if {@code x > y}
1406      * @since 1.7
1407      */
1408     public static int compare(long x, long y) {
1409         return (x < y) ? -1 : ((x == y) ? 0 : 1);
1410     }
1411 
1412     /**
1413      * Compares two {@code long} values numerically treating the values
1414      * as unsigned.
1415      *
1416      * @param  x the first {@code long} to compare
1417      * @param  y the second {@code long} to compare
1418      * @return the value {@code 0} if {@code x == y}; a value less
1419      *         than {@code 0} if {@code x < y} as unsigned values; and
1420      *         a value greater than {@code 0} if {@code x > y} as
1421      *         unsigned values
1422      * @since 1.8
1423      */
1424     @IntrinsicCandidate
1425     public static int compareUnsigned(long x, long y) {
1426         return compare(x + MIN_VALUE, y + MIN_VALUE);
1427     }
1428 
1429 
1430     /**
1431      * Returns the unsigned quotient of dividing the first argument by
1432      * the second where each argument and the result is interpreted as
1433      * an unsigned value.
1434      *
1435      * <p>Note that in two's complement arithmetic, the three other
1436      * basic arithmetic operations of add, subtract, and multiply are
1437      * bit-wise identical if the two operands are regarded as both
1438      * being signed or both being unsigned.  Therefore separate {@code
1439      * addUnsigned}, etc. methods are not provided.
1440      *
1441      * @param dividend the value to be divided
1442      * @param divisor the value doing the dividing
1443      * @return the unsigned quotient of the first argument divided by
1444      * the second argument
1445      * @throws ArithmeticException if the divisor is zero
1446      * @see #remainderUnsigned
1447      * @since 1.8
1448      */
1449     @IntrinsicCandidate
1450     public static long divideUnsigned(long dividend, long divisor) {
1451         /* See Hacker's Delight (2nd ed), section 9.3 */
1452         if (divisor >= 0) {
1453             final long q = (dividend >>> 1) / divisor << 1;
1454             final long r = dividend - q * divisor;
1455             return q + ((r | ~(r - divisor)) >>> (Long.SIZE - 1));
1456         }
1457         return (dividend & ~(dividend - divisor)) >>> (Long.SIZE - 1);
1458     }
1459 
1460     /**
1461      * Returns the unsigned remainder from dividing the first argument
1462      * by the second where each argument and the result is interpreted
1463      * as an unsigned value.
1464      *
1465      * @param dividend the value to be divided
1466      * @param divisor the value doing the dividing
1467      * @return the unsigned remainder of the first argument divided by
1468      * the second argument
1469      * @throws ArithmeticException if the divisor is zero
1470      * @see #divideUnsigned
1471      * @since 1.8
1472      */
1473     @IntrinsicCandidate
1474     public static long remainderUnsigned(long dividend, long divisor) {
1475         /* See Hacker's Delight (2nd ed), section 9.3 */
1476         if (divisor >= 0) {
1477             final long q = (dividend >>> 1) / divisor << 1;
1478             final long r = dividend - q * divisor;
1479             /*
1480              * Here, 0 <= r < 2 * divisor
1481              * (1) When 0 <= r < divisor, the remainder is simply r.
1482              * (2) Otherwise the remainder is r - divisor.
1483              *
1484              * In case (1), r - divisor < 0. Applying ~ produces a long with
1485              * sign bit 0, so >> produces 0. The returned value is thus r.
1486              *
1487              * In case (2), a similar reasoning shows that >> produces -1,
1488              * so the returned value is r - divisor.
1489              */
1490             return r - ((~(r - divisor) >> (Long.SIZE - 1)) & divisor);
1491         }
1492         /*
1493          * (1) When dividend >= 0, the remainder is dividend.
1494          * (2) Otherwise
1495          *      (2.1) When dividend < divisor, the remainder is dividend.
1496          *      (2.2) Otherwise the remainder is dividend - divisor
1497          *
1498          * A reasoning similar to the above shows that the returned value
1499          * is as expected.
1500          */
1501         return dividend - (((dividend & ~(dividend - divisor)) >> (Long.SIZE - 1)) & divisor);
1502     }
1503 
1504     // Bit Twiddling
1505 
1506     /**
1507      * The number of bits used to represent a {@code long} value in two's
1508      * complement binary form.
1509      *
1510      * @since 1.5
1511      */
1512     @Native public static final int SIZE = 64;
1513 
1514     /**
1515      * The number of bytes used to represent a {@code long} value in two's
1516      * complement binary form.
1517      *
1518      * @since 1.8
1519      */
1520     public static final int BYTES = SIZE / Byte.SIZE;
1521 
1522     /**
1523      * Returns a {@code long} value with at most a single one-bit, in the
1524      * position of the highest-order ("leftmost") one-bit in the specified
1525      * {@code long} value.  Returns zero if the specified value has no
1526      * one-bits in its two's complement binary representation, that is, if it
1527      * is equal to zero.
1528      *
1529      * @param i the value whose highest one bit is to be computed
1530      * @return a {@code long} value with a single one-bit, in the position
1531      *     of the highest-order one-bit in the specified value, or zero if
1532      *     the specified value is itself equal to zero.
1533      * @since 1.5
1534      */
1535     public static long highestOneBit(long i) {
1536         return i & (MIN_VALUE >>> numberOfLeadingZeros(i));
1537     }
1538 
1539     /**
1540      * Returns a {@code long} value with at most a single one-bit, in the
1541      * position of the lowest-order ("rightmost") one-bit in the specified
1542      * {@code long} value.  Returns zero if the specified value has no
1543      * one-bits in its two's complement binary representation, that is, if it
1544      * is equal to zero.
1545      *
1546      * @param i the value whose lowest one bit is to be computed
1547      * @return a {@code long} value with a single one-bit, in the position
1548      *     of the lowest-order one-bit in the specified value, or zero if
1549      *     the specified value is itself equal to zero.
1550      * @since 1.5
1551      */
1552     public static long lowestOneBit(long i) {
1553         // HD, Section 2-1
1554         return i & -i;
1555     }
1556 
1557     /**
1558      * Returns the number of zero bits preceding the highest-order
1559      * ("leftmost") one-bit in the two's complement binary representation
1560      * of the specified {@code long} value.  Returns 64 if the
1561      * specified value has no one-bits in its two's complement representation,
1562      * in other words if it is equal to zero.
1563      *
1564      * <p>Note that this method is closely related to the logarithm base 2.
1565      * For all positive {@code long} values x:
1566      * <ul>
1567      * <li>floor(log<sub>2</sub>(x)) = {@code 63 - numberOfLeadingZeros(x)}
1568      * <li>ceil(log<sub>2</sub>(x)) = {@code 64 - numberOfLeadingZeros(x - 1)}
1569      * </ul>
1570      *
1571      * @param i the value whose number of leading zeros is to be computed
1572      * @return the number of zero bits preceding the highest-order
1573      *     ("leftmost") one-bit in the two's complement binary representation
1574      *     of the specified {@code long} value, or 64 if the value
1575      *     is equal to zero.
1576      * @since 1.5
1577      */
1578     @IntrinsicCandidate
1579     public static int numberOfLeadingZeros(long i) {
1580         int x = (int)(i >>> 32);
1581         return x == 0 ? 32 + Integer.numberOfLeadingZeros((int)i)
1582                 : Integer.numberOfLeadingZeros(x);
1583     }
1584 
1585     /**
1586      * Returns the number of zero bits following the lowest-order ("rightmost")
1587      * one-bit in the two's complement binary representation of the specified
1588      * {@code long} value.  Returns 64 if the specified value has no
1589      * one-bits in its two's complement representation, in other words if it is
1590      * equal to zero.
1591      *
1592      * @param i the value whose number of trailing zeros is to be computed
1593      * @return the number of zero bits following the lowest-order ("rightmost")
1594      *     one-bit in the two's complement binary representation of the
1595      *     specified {@code long} value, or 64 if the value is equal
1596      *     to zero.
1597      * @since 1.5
1598      */
1599     @IntrinsicCandidate
1600     public static int numberOfTrailingZeros(long i) {
1601         int x = (int)i;
1602         return x == 0 ? 32 + Integer.numberOfTrailingZeros((int)(i >>> 32))
1603                 : Integer.numberOfTrailingZeros(x);
1604     }
1605 
1606     /**
1607      * Returns the number of one-bits in the two's complement binary
1608      * representation of the specified {@code long} value.  This function is
1609      * sometimes referred to as the <i>population count</i>.
1610      *
1611      * @param i the value whose bits are to be counted
1612      * @return the number of one-bits in the two's complement binary
1613      *     representation of the specified {@code long} value.
1614      * @since 1.5
1615      */
1616      @IntrinsicCandidate
1617      public static int bitCount(long i) {
1618         // HD, Figure 5-2
1619         i = i - ((i >>> 1) & 0x5555555555555555L);
1620         i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L);
1621         i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL;
1622         i = i + (i >>> 8);
1623         i = i + (i >>> 16);
1624         i = i + (i >>> 32);
1625         return (int)i & 0x7f;
1626      }
1627 
1628     /**
1629      * Returns the value obtained by rotating the two's complement binary
1630      * representation of the specified {@code long} value left by the
1631      * specified number of bits.  (Bits shifted out of the left hand, or
1632      * high-order, side reenter on the right, or low-order.)
1633      *
1634      * <p>Note that left rotation with a negative distance is equivalent to
1635      * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
1636      * distance)}.  Note also that rotation by any multiple of 64 is a
1637      * no-op, so all but the last six bits of the rotation distance can be
1638      * ignored, even if the distance is negative: {@code rotateLeft(val,
1639      * distance) == rotateLeft(val, distance & 0x3F)}.
1640      *
1641      * @param i the value whose bits are to be rotated left
1642      * @param distance the number of bit positions to rotate left
1643      * @return the value obtained by rotating the two's complement binary
1644      *     representation of the specified {@code long} value left by the
1645      *     specified number of bits.
1646      * @since 1.5
1647      */
1648     public static long rotateLeft(long i, int distance) {
1649         return (i << distance) | (i >>> -distance);
1650     }
1651 
1652     /**
1653      * Returns the value obtained by rotating the two's complement binary
1654      * representation of the specified {@code long} value right by the
1655      * specified number of bits.  (Bits shifted out of the right hand, or
1656      * low-order, side reenter on the left, or high-order.)
1657      *
1658      * <p>Note that right rotation with a negative distance is equivalent to
1659      * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
1660      * distance)}.  Note also that rotation by any multiple of 64 is a
1661      * no-op, so all but the last six bits of the rotation distance can be
1662      * ignored, even if the distance is negative: {@code rotateRight(val,
1663      * distance) == rotateRight(val, distance & 0x3F)}.
1664      *
1665      * @param i the value whose bits are to be rotated right
1666      * @param distance the number of bit positions to rotate right
1667      * @return the value obtained by rotating the two's complement binary
1668      *     representation of the specified {@code long} value right by the
1669      *     specified number of bits.
1670      * @since 1.5
1671      */
1672     public static long rotateRight(long i, int distance) {
1673         return (i >>> distance) | (i << -distance);
1674     }
1675 
1676     /**
1677      * Returns the value obtained by reversing the order of the bits in the
1678      * two's complement binary representation of the specified {@code long}
1679      * value.
1680      *
1681      * @param i the value to be reversed
1682      * @return the value obtained by reversing order of the bits in the
1683      *     specified {@code long} value.
1684      * @since 1.5
1685      */
1686     @IntrinsicCandidate
1687     public static long reverse(long i) {
1688         // HD, Figure 7-1
1689         i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L;
1690         i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L;
1691         i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL;
1692 
1693         return reverseBytes(i);
1694     }
1695 
1696     /**
1697      * Returns the value obtained by compressing the bits of the
1698      * specified {@code long} value, {@code i}, in accordance with
1699      * the specified bit mask.
1700      * <p>
1701      * For each one-bit value {@code mb} of the mask, from least
1702      * significant to most significant, the bit value of {@code i} at
1703      * the same bit location as {@code mb} is assigned to the compressed
1704      * value contiguously starting from the least significant bit location.
1705      * All the upper remaining bits of the compressed value are set
1706      * to zero.
1707      *
1708      * @apiNote
1709      * Consider the simple case of compressing the digits of a hexadecimal
1710      * value:
1711      * {@snippet lang="java" :
1712      * // Compressing drink to food
1713      * compress(0xCAFEBABEL, 0xFF00FFF0L) == 0xCABABL
1714      * }
1715      * Starting from the least significant hexadecimal digit at position 0
1716      * from the right, the mask {@code 0xFF00FFF0} selects hexadecimal digits
1717      * at positions 1, 2, 3, 6 and 7 of {@code 0xCAFEBABE}. The selected digits
1718      * occur in the resulting compressed value contiguously from digit position
1719      * 0 in the same order.
1720      * <p>
1721      * The following identities all return {@code true} and are helpful to
1722      * understand the behaviour of {@code compress}:
1723      * {@snippet lang="java" :
1724      * // Returns 1 if the bit at position n is one
1725      * compress(x, 1L << n) == (x >> n & 1)
1726      *
1727      * // Logical shift right
1728      * compress(x, -1L << n) == x >>> n
1729      *
1730      * // Any bits not covered by the mask are ignored
1731      * compress(x, m) == compress(x & m, m)
1732      *
1733      * // Compressing a value by itself
1734      * compress(m, m) == (m == -1 || m == 0) ? m : (1L << bitCount(m)) - 1
1735      *
1736      * // Expanding then compressing with the same mask
1737      * compress(expand(x, m), m) == x & compress(m, m)
1738      * }
1739      * <p>
1740      * The Sheep And Goats (SAG) operation (see Hacker's Delight, Second Edition, section 7.7)
1741      * can be implemented as follows:
1742      * {@snippet lang="java" :
1743      * long compressLeft(long i, long mask) {
1744      *     // This implementation follows the description in Hacker's Delight which
1745      *     // is informative. A more optimal implementation is:
1746      *     //   Long.compress(i, mask) << -Long.bitCount(mask)
1747      *     return Long.reverse(
1748      *         Long.compress(Long.reverse(i), Long.reverse(mask)));
1749      * }
1750      *
1751      * long sag(long i, long mask) {
1752      *     return compressLeft(i, mask) | Long.compress(i, ~mask);
1753      * }
1754      *
1755      * // Separate the sheep from the goats
1756      * sag(0x00000000_CAFEBABEL, 0xFFFFFFFF_FF00FFF0L) == 0x00000000_CABABFEEL
1757      * }
1758      *
1759      * @param i the value whose bits are to be compressed
1760      * @param mask the bit mask
1761      * @return the compressed value
1762      * @see #expand
1763      * @since 19
1764      */
1765     @IntrinsicCandidate
1766     public static long compress(long i, long mask) {
1767         // See Hacker's Delight (2nd ed) section 7.4 Compress, or Generalized Extract
1768 
1769         i = i & mask; // Clear irrelevant bits
1770         long maskCount = ~mask << 1; // Count 0's to right
1771 
1772         for (int j = 0; j < 6; j++) {
1773             // Parallel prefix
1774             // Mask prefix identifies bits of the mask that have an odd number of 0's to the right
1775             long maskPrefix = parallelSuffix(maskCount);
1776             // Bits to move
1777             long maskMove = maskPrefix & mask;
1778             // Compress mask
1779             mask = (mask ^ maskMove) | (maskMove >>> (1 << j));
1780             // Bits of i to be moved
1781             long t = i & maskMove;
1782             // Compress i
1783             i = (i ^ t) | (t >>> (1 << j));
1784             // Adjust the mask count by identifying bits that have 0 to the right
1785             maskCount = maskCount & ~maskPrefix;
1786         }
1787         return i;
1788     }
1789 
1790     /**
1791      * Returns the value obtained by expanding the bits of the
1792      * specified {@code long} value, {@code i}, in accordance with
1793      * the specified bit mask.
1794      * <p>
1795      * For each one-bit value {@code mb} of the mask, from least
1796      * significant to most significant, the next contiguous bit value
1797      * of {@code i} starting at the least significant bit is assigned
1798      * to the expanded value at the same bit location as {@code mb}.
1799      * All other remaining bits of the expanded value are set to zero.
1800      *
1801      * @apiNote
1802      * Consider the simple case of expanding the digits of a hexadecimal
1803      * value:
1804      * {@snippet lang="java" :
1805      * expand(0x0000CABABL, 0xFF00FFF0L) == 0xCA00BAB0L
1806      * }
1807      * Starting from the least significant hexadecimal digit at position 0
1808      * from the right, the mask {@code 0xFF00FFF0} selects the first five
1809      * hexadecimal digits of {@code 0x0000CABAB}. The selected digits occur
1810      * in the resulting expanded value in order at positions 1, 2, 3, 6, and 7.
1811      * <p>
1812      * The following identities all return {@code true} and are helpful to
1813      * understand the behaviour of {@code expand}:
1814      * {@snippet lang="java" :
1815      * // Logically shift right the bit at position 0
1816      * expand(x, 1L << n) == (x & 1) << n
1817      *
1818      * // Logically shift right
1819      * expand(x, -1L << n) == x << n
1820      *
1821      * // Expanding all bits returns the mask
1822      * expand(-1L, m) == m
1823      *
1824      * // Any bits not covered by the mask are ignored
1825      * expand(x, m) == expand(x, m) & m
1826      *
1827      * // Compressing then expanding with the same mask
1828      * expand(compress(x, m), m) == x & m
1829      * }
1830      * <p>
1831      * The select operation for determining the position of the one-bit with
1832      * index {@code n} in a {@code long} value can be implemented as follows:
1833      * {@snippet lang="java" :
1834      * long select(long i, long n) {
1835      *     // the one-bit in i (the mask) with index n
1836      *     long nthBit = Long.expand(1L << n, i);
1837      *     // the bit position of the one-bit with index n
1838      *     return Long.numberOfTrailingZeros(nthBit);
1839      * }
1840      *
1841      * // The one-bit with index 0 is at bit position 1
1842      * select(0b10101010_10101010, 0) == 1
1843      * // The one-bit with index 3 is at bit position 7
1844      * select(0b10101010_10101010, 3) == 7
1845      * }
1846      *
1847      * @param i the value whose bits are to be expanded
1848      * @param mask the bit mask
1849      * @return the expanded value
1850      * @see #compress
1851      * @since 19
1852      */
1853     @IntrinsicCandidate
1854     public static long expand(long i, long mask) {
1855         // Save original mask
1856         long originalMask = mask;
1857         // Count 0's to right
1858         long maskCount = ~mask << 1;
1859         long maskPrefix = parallelSuffix(maskCount);
1860         // Bits to move
1861         long maskMove1 = maskPrefix & mask;
1862         // Compress mask
1863         mask = (mask ^ maskMove1) | (maskMove1 >>> (1 << 0));
1864         maskCount = maskCount & ~maskPrefix;
1865 
1866         maskPrefix = parallelSuffix(maskCount);
1867         // Bits to move
1868         long maskMove2 = maskPrefix & mask;
1869         // Compress mask
1870         mask = (mask ^ maskMove2) | (maskMove2 >>> (1 << 1));
1871         maskCount = maskCount & ~maskPrefix;
1872 
1873         maskPrefix = parallelSuffix(maskCount);
1874         // Bits to move
1875         long maskMove3 = maskPrefix & mask;
1876         // Compress mask
1877         mask = (mask ^ maskMove3) | (maskMove3 >>> (1 << 2));
1878         maskCount = maskCount & ~maskPrefix;
1879 
1880         maskPrefix = parallelSuffix(maskCount);
1881         // Bits to move
1882         long maskMove4 = maskPrefix & mask;
1883         // Compress mask
1884         mask = (mask ^ maskMove4) | (maskMove4 >>> (1 << 3));
1885         maskCount = maskCount & ~maskPrefix;
1886 
1887         maskPrefix = parallelSuffix(maskCount);
1888         // Bits to move
1889         long maskMove5 = maskPrefix & mask;
1890         // Compress mask
1891         mask = (mask ^ maskMove5) | (maskMove5 >>> (1 << 4));
1892         maskCount = maskCount & ~maskPrefix;
1893 
1894         maskPrefix = parallelSuffix(maskCount);
1895         // Bits to move
1896         long maskMove6 = maskPrefix & mask;
1897 
1898         long t = i << (1 << 5);
1899         i = (i & ~maskMove6) | (t & maskMove6);
1900         t = i << (1 << 4);
1901         i = (i & ~maskMove5) | (t & maskMove5);
1902         t = i << (1 << 3);
1903         i = (i & ~maskMove4) | (t & maskMove4);
1904         t = i << (1 << 2);
1905         i = (i & ~maskMove3) | (t & maskMove3);
1906         t = i << (1 << 1);
1907         i = (i & ~maskMove2) | (t & maskMove2);
1908         t = i << (1 << 0);
1909         i = (i & ~maskMove1) | (t & maskMove1);
1910 
1911         // Clear irrelevant bits
1912         return i & originalMask;
1913     }
1914 
1915     @ForceInline
1916     private static long parallelSuffix(long maskCount) {
1917         long maskPrefix = maskCount ^ (maskCount << 1);
1918         maskPrefix = maskPrefix ^ (maskPrefix << 2);
1919         maskPrefix = maskPrefix ^ (maskPrefix << 4);
1920         maskPrefix = maskPrefix ^ (maskPrefix << 8);
1921         maskPrefix = maskPrefix ^ (maskPrefix << 16);
1922         maskPrefix = maskPrefix ^ (maskPrefix << 32);
1923         return maskPrefix;
1924     }
1925 
1926     /**
1927      * Returns the signum function of the specified {@code long} value.  (The
1928      * return value is -1 if the specified value is negative; 0 if the
1929      * specified value is zero; and 1 if the specified value is positive.)
1930      *
1931      * @param i the value whose signum is to be computed
1932      * @return the signum function of the specified {@code long} value.
1933      * @since 1.5
1934      */
1935     public static int signum(long i) {
1936         // HD, Section 2-7
1937         return (int) ((i >> 63) | (-i >>> 63));
1938     }
1939 
1940     /**
1941      * Returns the value obtained by reversing the order of the bytes in the
1942      * two's complement representation of the specified {@code long} value.
1943      *
1944      * @param i the value whose bytes are to be reversed
1945      * @return the value obtained by reversing the bytes in the specified
1946      *     {@code long} value.
1947      * @since 1.5
1948      */
1949     @IntrinsicCandidate
1950     public static long reverseBytes(long i) {
1951         i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
1952         return (i << 48) | ((i & 0xffff0000L) << 16) |
1953             ((i >>> 16) & 0xffff0000L) | (i >>> 48);
1954     }
1955 
1956     /**
1957      * Adds two {@code long} values together as per the + operator.
1958      *
1959      * @param a the first operand
1960      * @param b the second operand
1961      * @return the sum of {@code a} and {@code b}
1962      * @see java.util.function.BinaryOperator
1963      * @since 1.8
1964      */
1965     public static long sum(long a, long b) {
1966         return a + b;
1967     }
1968 
1969     /**
1970      * Returns the greater of two {@code long} values
1971      * as if by calling {@link Math#max(long, long) Math.max}.
1972      *
1973      * @param a the first operand
1974      * @param b the second operand
1975      * @return the greater of {@code a} and {@code b}
1976      * @see java.util.function.BinaryOperator
1977      * @since 1.8
1978      */
1979     public static long max(long a, long b) {
1980         return Math.max(a, b);
1981     }
1982 
1983     /**
1984      * Returns the smaller of two {@code long} values
1985      * as if by calling {@link Math#min(long, long) Math.min}.
1986      *
1987      * @param a the first operand
1988      * @param b the second operand
1989      * @return the smaller of {@code a} and {@code b}
1990      * @see java.util.function.BinaryOperator
1991      * @since 1.8
1992      */
1993     public static long min(long a, long b) {
1994         return Math.min(a, b);
1995     }
1996 
1997     /**
1998      * Returns an {@link Optional} containing the nominal descriptor for this
1999      * instance, which is the instance itself.
2000      *
2001      * @return an {@link Optional} describing the {@linkplain Long} instance
2002      * @since 12
2003      */
2004     @Override
2005     public Optional<Long> describeConstable() {
2006         return Optional.of(this);
2007     }
2008 
2009     /**
2010      * Resolves this instance as a {@link ConstantDesc}, the result of which is
2011      * the instance itself.
2012      *
2013      * @param lookup ignored
2014      * @return the {@linkplain Long} instance
2015      * @since 12
2016      */
2017     @Override
2018     public Long resolveConstantDesc(MethodHandles.Lookup lookup) {
2019         return this;
2020     }
2021 
2022     /** use serialVersionUID from JDK 1.0.2 for interoperability */
2023     @java.io.Serial
2024     @Native private static final long serialVersionUID = 4290774380558885855L;
2025 }