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