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