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