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