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