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