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