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         return parseLong(s, radix, 0);
 551     }
 552 
 553     /**
 554      * Extend upon Long.parseLong(String, int) by providing a start offset to enable parsing
 555      * substrings without creating intermediary objects
 556      * @see java.lang.Long#parseLong(String, int)
 557      *
 558      * @param start the start position in s to parse from, inclusive
 559      */
 560     static long parseLong(CharSequence s, int radix, int start)
 561             throws NumberFormatException {
 562         if (s == null) {
 563             throw new NumberFormatException("null");
 564         }
 565         return parseLong(s, radix, start, s.length());
 566     }
 567 
 568     /**
 569      * Extend upon Long.parseLong(String, int) by providing a start and end offset to enable parsing
 570      * substrings without creating intermediary objects
 571      * @see java.lang.Long#parseLong(String, int)
 572      * @param start the start position in s to parse from, inclusive
 573      * @param end the end position in s to parse to, exclusive
 574      */
 575     static long parseLong(CharSequence s, int radix, int start, int end)
 576             throws NumberFormatException {
 577         if (s == null) {
 578             throw new NumberFormatException("null");
 579         }
 580 
 581         if (radix < Character.MIN_RADIX) {
 582             throw new NumberFormatException("radix " + radix +
 583                     " less than Character.MIN_RADIX");
 584         }
 585 
 586         if (radix > Character.MAX_RADIX) {
 587             throw new NumberFormatException("radix " + radix +
 588                     " greater than Character.MAX_RADIX");
 589         }
 590 
 591         if (start < 0 || start >= end) {
 592             throw new NumberFormatException("start position out of bounds");
 593         }
 594 
 595         if (start == end) {
 596             throw NumberFormatException.forInputString("");
 597         }
 598 
 599         if (end > s.length()) {
 600             throw new NumberFormatException("end position out of bounds");
 601         }
 602 
 603         long result = 0;
 604         boolean negative = false;
 605         int i = start;
 606         long limit = -Long.MAX_VALUE;
 607         long multmin;
 608         int digit;
 609 
 610         char firstChar = s.charAt(i);
 611         if (firstChar < '0') { // Possible leading "+" or "-"
 612             if (firstChar == '-') {
 613                 negative = true;
 614                 limit = Long.MIN_VALUE;
 615             } else if (firstChar != '+') {
 616                 throw NumberFormatException.forInputString(
 617                         s.subSequence(start, end).toString());
 618             }
 619             if (end == start + 1) { // Cannot have lone "+" or "-"
 620                 throw NumberFormatException.forInputString(
 621                         s.subSequence(start, end).toString());
 622             }
 623             i++;
 624         }
 625         multmin = limit / radix;
 626         while (i < end) {
 627             // Accumulating negatively avoids surprises near MAX_VALUE
 628             digit = Character.digit(s.charAt(i++), radix);
 629             if (digit < 0) {
 630                 throw NumberFormatException.forInputString(
 631                         s.subSequence(start, end).toString());
 632             }
 633             if (result < multmin) {
 634                 throw NumberFormatException.forInputString(
 635                         s.subSequence(start, end).toString());
 636             }
 637             result *= radix;
 638             if (result < limit + digit) {
 639                 throw NumberFormatException.forInputString(
 640                         s.subSequence(start, end).toString());
 641             }
 642             result -= digit;
 643         }
 644         return negative ? result : -result;
 645     }
 646 
 647     /**
 648      * Parses the string argument as a signed decimal {@code long}.
 649      * The characters in the string must all be decimal digits, except
 650      * that the first character may be an ASCII minus sign {@code '-'}
 651      * ({@code \u005Cu002D'}) to indicate a negative value or an
 652      * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
 653      * indicate a positive value. The resulting {@code long} value is
 654      * returned, exactly as if the argument and the radix {@code 10}
 655      * were given as arguments to the {@link
 656      * #parseLong(java.lang.String, int)} method.
 657      *
 658      * <p>Note that neither the character {@code L}
 659      * ({@code '\u005Cu004C'}) nor {@code l}
 660      * ({@code '\u005Cu006C'}) is permitted to appear at the end
 661      * of the string as a type indicator, as would be permitted in
 662      * Java programming language source code.
 663      *
 664      * @param      s   a {@code String} containing the {@code long}
 665      *             representation to be parsed
 666      * @return     the {@code long} represented by the argument in
 667      *             decimal.
 668      * @throws     NumberFormatException  if the string does not contain a
 669      *             parsable {@code long}.
 670      */
 671     public static long parseLong(String s) throws NumberFormatException {
 672         return parseLong(s, 10);
 673     }
 674 
 675     /**
 676      * Parses the string argument as an unsigned {@code long} in the
 677      * radix specified by the second argument.  An unsigned integer
 678      * maps the values usually associated with negative numbers to
 679      * positive numbers larger than {@code MAX_VALUE}.
 680      *
 681      * The characters in the string must all be digits of the
 682      * specified radix (as determined by whether {@link
 683      * java.lang.Character#digit(char, int)} returns a nonnegative
 684      * value), except that the first character may be an ASCII plus
 685      * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting
 686      * integer value is returned.
 687      *
 688      * <p>An exception of type {@code NumberFormatException} is
 689      * thrown if any of the following situations occurs:
 690      * <ul>
 691      * <li>The first argument is {@code null} or is a string of
 692      * length zero.
 693      *
 694      * <li>The radix is either smaller than
 695      * {@link java.lang.Character#MIN_RADIX} or
 696      * larger than {@link java.lang.Character#MAX_RADIX}.
 697      *
 698      * <li>Any character of the string is not a digit of the specified
 699      * radix, except that the first character may be a plus sign
 700      * {@code '+'} ({@code '\u005Cu002B'}) provided that the
 701      * string is longer than length 1.
 702      *
 703      * <li>The value represented by the string is larger than the
 704      * largest unsigned {@code long}, 2<sup>64</sup>-1.
 705      *
 706      * </ul>
 707      *
 708      *
 709      * @param      s   the {@code String} containing the unsigned integer
 710      *                  representation to be parsed
 711      * @param      radix   the radix to be used while parsing {@code s}.
 712      * @return     the unsigned {@code long} represented by the string
 713      *             argument in the specified radix.
 714      * @throws     NumberFormatException if the {@code String}
 715      *             does not contain a parsable {@code long}.
 716      * @since 1.8
 717      */
 718     public static long parseUnsignedLong(String s, int radix)
 719                 throws NumberFormatException {
 720         if (s == null)  {
 721             throw new NumberFormatException("null");
 722         }
 723         return parseUnsignedLong(s, radix, 0);
 724     }
 725 
 726     /**
 727      * Extend upon Long.parseUnsignedLong(String, int) by providing a start offset
 728      * to enable parsing substrings without creating intermediary objects
 729      * @see java.lang.Long#parseUnsignedLong(String, int)
 730      * @param start the start position in s to parse from, inclusive
 731      */
 732     static long parseUnsignedLong(CharSequence s, int radix, int start) {
 733         if (s == null)  {
 734             throw new NumberFormatException("null");
 735         }
 736         return parseUnsignedLong(s, radix, start, s.length());
 737     }
 738 
 739     /**
 740      * Extend upon Long.parseUnsignedLong(String, int) by providing a start offset to enable parsing
 741      * substrings without creating intermediary objects
 742      * @see java.lang.Long#parseUnsignedLong(String, int)
 743      * @param start the start position in s to parse from, inclusive
 744      * @param end the end position in s to parse to, exclusive
 745      */
 746     static long parseUnsignedLong(CharSequence s, int radix, int start, int end) {
 747         if (s == null) {
 748             throw new NumberFormatException("null");
 749         }
 750 
 751         if (radix < Character.MIN_RADIX) {
 752             throw new NumberFormatException("radix " + radix +
 753                     " less than Character.MIN_RADIX");
 754         }
 755 
 756         if (radix > Character.MAX_RADIX) {
 757             throw new NumberFormatException("radix " + radix +
 758                     " greater than Character.MAX_RADIX");
 759         }
 760 
 761         if (start < 0 || start > end) {
 762             throw new NumberFormatException("start position out of bounds");
 763         }
 764 
 765         if (end <= start || end > s.length()) {
 766             throw new NumberFormatException("end position out of bounds");
 767         }
 768 
 769         int count = end - start;
 770         char firstChar = s.charAt(start);
 771         if (firstChar == '-') {
 772             throw new NumberFormatException(String.format("Illegal leading minus sign " +
 773                     "on unsigned string %s.", s.subSequence(start, end)));
 774         } else {
 775             if (count <= 12 || // Long.MAX_VALUE in Character.MAX_RADIX is 13 digits
 776                     (radix == 10 && count <= 18) ) { // Long.MAX_VALUE in base 10 is 19 digits
 777                 return parseLong(s, radix, start, end);
 778             }
 779 
 780             // No need for range checks on end due to testing above.
 781             long first = parseLong(s, radix, start, end - 1);
 782             int second = Character.digit(s.charAt(end - 1), radix);
 783             if (second < 0) {
 784                 throw new NumberFormatException("Bad digit at end of " + s.subSequence(start, end));
 785             }
 786             long result = first * radix + second;
 787 
 788             /*
 789              * Test leftmost bits of multiprecision extension of first*radix
 790              * for overflow. The number of bits needed is defined by
 791              * GUARD_BIT = ceil(log2(Character.MAX_RADIX)) + 1 = 7. Then
 792              * int guard = radix*(int)(first >>> (64 - GUARD_BIT)) and
 793              * overflow is tested by splitting guard in the ranges
 794              * guard < 92, 92 <= guard < 128, and 128 <= guard, where
 795              * 92 = 128 - Character.MAX_RADIX. Note that guard cannot take
 796              * on a value which does not include a prime factor in the legal
 797              * radix range.
 798              */
 799             int guard = radix * (int) (first >>> 57);
 800             if (guard >= 128 ||
 801                     (result >= 0 && guard >= 128 - Character.MAX_RADIX)) {
 802                 /*
 803                  * For purposes of exposition, the programmatic statements
 804                  * below should be taken to be multi-precision, i.e., not
 805                  * subject to overflow.
 806                  *
 807                  * A) Condition guard >= 128:
 808                  * If guard >= 128 then first*radix >= 2^7 * 2^57 = 2^64
 809                  * hence always overflow.
 810                  *
 811                  * B) Condition guard < 92:
 812                  * Define left7 = first >>> 57.
 813                  * Given first = (left7 * 2^57) + (first & (2^57 - 1)) then
 814                  * result <= (radix*left7)*2^57 + radix*(2^57 - 1) + second.
 815                  * Thus if radix*left7 < 92, radix <= 36, and second < 36,
 816                  * then result < 92*2^57 + 36*(2^57 - 1) + 36 = 2^64 hence
 817                  * never overflow.
 818                  *
 819                  * C) Condition 92 <= guard < 128:
 820                  * first*radix + second >= radix*left7*2^57 + second
 821                  * so that first*radix + second >= 92*2^57 + 0 > 2^63
 822                  *
 823                  * D) Condition guard < 128:
 824                  * radix*first <= (radix*left7) * 2^57 + radix*(2^57 - 1)
 825                  * so
 826                  * radix*first + second <= (radix*left7) * 2^57 + radix*(2^57 - 1) + 36
 827                  * thus
 828                  * radix*first + second < 128 * 2^57 + 36*2^57 - radix + 36
 829                  * whence
 830                  * radix*first + second < 2^64 + 2^6*2^57 = 2^64 + 2^63
 831                  *
 832                  * E) Conditions C, D, and result >= 0:
 833                  * C and D combined imply the mathematical result
 834                  * 2^63 < first*radix + second < 2^64 + 2^63. The lower
 835                  * bound is therefore negative as a signed long, but the
 836                  * upper bound is too small to overflow again after the
 837                  * signed long overflows to positive above 2^64 - 1. Hence
 838                  * result >= 0 implies overflow given C and D.
 839                  */
 840                 throw new NumberFormatException(String.format("String value %s exceeds " +
 841                         "range of unsigned long.", s.subSequence(start, end)));
 842             }
 843             return result;
 844         }
 845     }
 846 
 847     /**
 848      * Parses the string argument as an unsigned decimal {@code long}. The
 849      * characters in the string must all be decimal digits, except
 850      * that the first character may be an an ASCII plus sign {@code
 851      * '+'} ({@code '\u005Cu002B'}). The resulting integer value
 852      * is returned, exactly as if the argument and the radix 10 were
 853      * given as arguments to the {@link
 854      * #parseUnsignedLong(java.lang.String, int)} method.
 855      *
 856      * @param s   a {@code String} containing the unsigned {@code long}
 857      *            representation to be parsed
 858      * @return    the unsigned {@code long} value represented by the decimal string argument
 859      * @throws    NumberFormatException  if the string does not contain a
 860      *            parsable unsigned integer.
 861      * @since 1.8
 862      */
 863     public static long parseUnsignedLong(String s) throws NumberFormatException {
 864         return parseUnsignedLong(s, 10);
 865     }
 866 
 867     /**
 868      * Returns a {@code Long} object holding the value
 869      * extracted from the specified {@code String} when parsed
 870      * with the radix given by the second argument.  The first
 871      * argument is interpreted as representing a signed
 872      * {@code long} in the radix specified by the second
 873      * argument, exactly as if the arguments were given to the {@link
 874      * #parseLong(java.lang.String, int)} method. The result is a
 875      * {@code Long} object that represents the {@code long}
 876      * value specified by the string.
 877      *
 878      * <p>In other words, this method returns a {@code Long} object equal
 879      * to the value of:
 880      *
 881      * <blockquote>
 882      *  {@code new Long(Long.parseLong(s, radix))}
 883      * </blockquote>
 884      *
 885      * @param      s       the string to be parsed
 886      * @param      radix   the radix to be used in interpreting {@code s}
 887      * @return     a {@code Long} object holding the value
 888      *             represented by the string argument in the specified
 889      *             radix.
 890      * @throws     NumberFormatException  If the {@code String} does not
 891      *             contain a parsable {@code long}.
 892      */
 893     public static Long valueOf(String s, int radix) throws NumberFormatException {
 894         return Long.valueOf(parseLong(s, radix));
 895     }
 896 
 897     /**
 898      * Returns a {@code Long} object holding the value
 899      * of the specified {@code String}. The argument is
 900      * interpreted as representing a signed decimal {@code long},
 901      * exactly as if the argument were given to the {@link
 902      * #parseLong(java.lang.String)} method. The result is a
 903      * {@code Long} object that represents the integer value
 904      * specified by the string.
 905      *
 906      * <p>In other words, this method returns a {@code Long} object
 907      * equal to the value of:
 908      *
 909      * <blockquote>
 910      *  {@code new Long(Long.parseLong(s))}
 911      * </blockquote>
 912      *
 913      * @param      s   the string to be parsed.
 914      * @return     a {@code Long} object holding the value
 915      *             represented by the string argument.
 916      * @throws     NumberFormatException  If the string cannot be parsed
 917      *             as a {@code long}.
 918      */
 919     public static Long valueOf(String s) throws NumberFormatException
 920     {
 921         return Long.valueOf(parseLong(s, 10));
 922     }
 923 
 924     private static class LongCache {
 925         private LongCache(){}
 926 
 927         static final Long cache[] = new Long[-(-128) + 127 + 1];
 928 
 929         static {
 930             for(int i = 0; i < cache.length; i++)
 931                 cache[i] = new Long(i - 128);
 932         }
 933     }
 934 
 935     /**
 936      * Returns a {@code Long} instance representing the specified
 937      * {@code long} value.
 938      * If a new {@code Long} instance is not required, this method
 939      * should generally be used in preference to the constructor
 940      * {@link #Long(long)}, as this method is likely to yield
 941      * significantly better space and time performance by caching
 942      * frequently requested values.
 943      *
 944      * Note that unlike the {@linkplain Integer#valueOf(int)
 945      * corresponding method} in the {@code Integer} class, this method
 946      * is <em>not</em> required to cache values within a particular
 947      * range.
 948      *
 949      * @param  l a long value.
 950      * @return a {@code Long} instance representing {@code l}.
 951      * @since  1.5
 952      */
 953     public static Long valueOf(long l) {
 954         final int offset = 128;
 955         if (l >= -128 && l <= 127) { // will cache
 956             return LongCache.cache[(int)l + offset];
 957         }
 958         return new Long(l);
 959     }
 960 
 961     /**
 962      * Decodes a {@code String} into a {@code Long}.
 963      * Accepts decimal, hexadecimal, and octal numbers given by the
 964      * following grammar:
 965      *
 966      * <blockquote>
 967      * <dl>
 968      * <dt><i>DecodableString:</i>
 969      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
 970      * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
 971      * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
 972      * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
 973      * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
 974      *
 975      * <dt><i>Sign:</i>
 976      * <dd>{@code -}
 977      * <dd>{@code +}
 978      * </dl>
 979      * </blockquote>
 980      *
 981      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
 982      * are as defined in section 3.10.1 of
 983      * <cite>The Java&trade; Language Specification</cite>,
 984      * except that underscores are not accepted between digits.
 985      *
 986      * <p>The sequence of characters following an optional
 987      * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
 988      * "{@code #}", or leading zero) is parsed as by the {@code
 989      * Long.parseLong} method with the indicated radix (10, 16, or 8).
 990      * This sequence of characters must represent a positive value or
 991      * a {@link NumberFormatException} will be thrown.  The result is
 992      * negated if first character of the specified {@code String} is
 993      * the minus sign.  No whitespace characters are permitted in the
 994      * {@code String}.
 995      *
 996      * @param     nm the {@code String} to decode.
 997      * @return    a {@code Long} object holding the {@code long}
 998      *            value represented by {@code nm}
 999      * @throws    NumberFormatException  if the {@code String} does not
1000      *            contain a parsable {@code long}.
1001      * @see java.lang.Long#parseLong(String, int)
1002      * @since 1.2
1003      */
1004     public static Long decode(String nm) throws NumberFormatException {
1005         int radix = 10;
1006         int index = 0;
1007         boolean negative = false;
1008         Long result;
1009 
1010         if (nm.length() == 0)
1011             throw new NumberFormatException("Zero length string");
1012         char firstChar = nm.charAt(0);
1013         // Handle sign, if present
1014         if (firstChar == '-') {
1015             negative = true;
1016             index++;
1017         } else if (firstChar == '+')
1018             index++;
1019 
1020         // Handle radix specifier, if present
1021         if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
1022             index += 2;
1023             radix = 16;
1024         }
1025         else if (nm.startsWith("#", index)) {
1026             index ++;
1027             radix = 16;
1028         }
1029         else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
1030             index ++;
1031             radix = 8;
1032         }
1033 
1034         if (nm.startsWith("-", index) || nm.startsWith("+", index))
1035             throw new NumberFormatException("Sign character in wrong position");
1036 
1037         try {
1038             result = Long.valueOf(nm.substring(index), radix);
1039             result = negative ? Long.valueOf(-result.longValue()) : result;
1040         } catch (NumberFormatException e) {
1041             // If number is Long.MIN_VALUE, we'll end up here. The next line
1042             // handles this case, and causes any genuine format error to be
1043             // rethrown.
1044             String constant = negative ? ("-" + nm.substring(index))
1045                                        : nm.substring(index);
1046             result = Long.valueOf(constant, radix);
1047         }
1048         return result;
1049     }
1050 
1051     /**
1052      * The value of the {@code Long}.
1053      *
1054      * @serial
1055      */
1056     private final long value;
1057 
1058     /**
1059      * Constructs a newly allocated {@code Long} object that
1060      * represents the specified {@code long} argument.
1061      *
1062      * @param   value   the value to be represented by the
1063      *          {@code Long} object.
1064      */
1065     public Long(long value) {
1066         this.value = value;
1067     }
1068 
1069     /**
1070      * Constructs a newly allocated {@code Long} object that
1071      * represents the {@code long} value indicated by the
1072      * {@code String} parameter. The string is converted to a
1073      * {@code long} value in exactly the manner used by the
1074      * {@code parseLong} method for radix 10.
1075      *
1076      * @param      s   the {@code String} to be converted to a
1077      *             {@code Long}.
1078      * @throws     NumberFormatException  if the {@code String} does not
1079      *             contain a parsable {@code long}.
1080      * @see        java.lang.Long#parseLong(java.lang.String, int)
1081      */
1082     public Long(String s) throws NumberFormatException {
1083         this.value = parseLong(s, 10);
1084     }
1085 
1086     /**
1087      * Returns the value of this {@code Long} as a {@code byte} after
1088      * a narrowing primitive conversion.
1089      * @jls 5.1.3 Narrowing Primitive Conversions
1090      */
1091     public byte byteValue() {
1092         return (byte)value;
1093     }
1094 
1095     /**
1096      * Returns the value of this {@code Long} as a {@code short} after
1097      * a narrowing primitive conversion.
1098      * @jls 5.1.3 Narrowing Primitive Conversions
1099      */
1100     public short shortValue() {
1101         return (short)value;
1102     }
1103 
1104     /**
1105      * Returns the value of this {@code Long} as an {@code int} after
1106      * a narrowing primitive conversion.
1107      * @jls 5.1.3 Narrowing Primitive Conversions
1108      */
1109     public int intValue() {
1110         return (int)value;
1111     }
1112 
1113     /**
1114      * Returns the value of this {@code Long} as a
1115      * {@code long} value.
1116      */
1117     public long longValue() {
1118         return value;
1119     }
1120 
1121     /**
1122      * Returns the value of this {@code Long} as a {@code float} after
1123      * a widening primitive conversion.
1124      * @jls 5.1.2 Widening Primitive Conversions
1125      */
1126     public float floatValue() {
1127         return (float)value;
1128     }
1129 
1130     /**
1131      * Returns the value of this {@code Long} as a {@code double}
1132      * after a widening primitive conversion.
1133      * @jls 5.1.2 Widening Primitive Conversions
1134      */
1135     public double doubleValue() {
1136         return (double)value;
1137     }
1138 
1139     /**
1140      * Returns a {@code String} object representing this
1141      * {@code Long}'s value.  The value is converted to signed
1142      * decimal representation and returned as a string, exactly as if
1143      * the {@code long} value were given as an argument to the
1144      * {@link java.lang.Long#toString(long)} method.
1145      *
1146      * @return  a string representation of the value of this object in
1147      *          base&nbsp;10.
1148      */
1149     public String toString() {
1150         return toString(value);
1151     }
1152 
1153     /**
1154      * Returns a hash code for this {@code Long}. The result is
1155      * the exclusive OR of the two halves of the primitive
1156      * {@code long} value held by this {@code Long}
1157      * object. That is, the hashcode is the value of the expression:
1158      *
1159      * <blockquote>
1160      *  {@code (int)(this.longValue()^(this.longValue()>>>32))}
1161      * </blockquote>
1162      *
1163      * @return  a hash code value for this object.
1164      */
1165     @Override
1166     public int hashCode() {
1167         return Long.hashCode(value);
1168     }
1169 
1170     /**
1171      * Returns a hash code for a {@code long} value; compatible with
1172      * {@code Long.hashCode()}.
1173      *
1174      * @param value the value to hash
1175      * @return a hash code value for a {@code long} value.
1176      * @since 1.8
1177      */
1178     public static int hashCode(long value) {
1179         return (int)(value ^ (value >>> 32));
1180     }
1181 
1182     /**
1183      * Compares this object to the specified object.  The result is
1184      * {@code true} if and only if the argument is not
1185      * {@code null} and is a {@code Long} object that
1186      * contains the same {@code long} value as this object.
1187      *
1188      * @param   obj   the object to compare with.
1189      * @return  {@code true} if the objects are the same;
1190      *          {@code false} otherwise.
1191      */
1192     public boolean equals(Object obj) {
1193         if (obj instanceof Long) {
1194             return value == ((Long)obj).longValue();
1195         }
1196         return false;
1197     }
1198 
1199     /**
1200      * Determines the {@code long} value of the system property
1201      * with the specified name.
1202      *
1203      * <p>The first argument is treated as the name of a system
1204      * property.  System properties are accessible through the {@link
1205      * java.lang.System#getProperty(java.lang.String)} method. The
1206      * string value of this property is then interpreted as a {@code
1207      * long} value using the grammar supported by {@link Long#decode decode}
1208      * and a {@code Long} object representing this value is returned.
1209      *
1210      * <p>If there is no property with the specified name, if the
1211      * specified name is empty or {@code null}, or if the property
1212      * does not have the correct numeric format, then {@code null} is
1213      * returned.
1214      *
1215      * <p>In other words, this method returns a {@code Long} object
1216      * equal to the value of:
1217      *
1218      * <blockquote>
1219      *  {@code getLong(nm, null)}
1220      * </blockquote>
1221      *
1222      * @param   nm   property name.
1223      * @return  the {@code Long} value of the property.
1224      * @throws  SecurityException for the same reasons as
1225      *          {@link System#getProperty(String) System.getProperty}
1226      * @see     java.lang.System#getProperty(java.lang.String)
1227      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
1228      */
1229     public static Long getLong(String nm) {
1230         return getLong(nm, null);
1231     }
1232 
1233     /**
1234      * Determines the {@code long} value of the system property
1235      * with the specified name.
1236      *
1237      * <p>The first argument is treated as the name of a system
1238      * property.  System properties are accessible through the {@link
1239      * java.lang.System#getProperty(java.lang.String)} method. The
1240      * string value of this property is then interpreted as a {@code
1241      * long} value using the grammar supported by {@link Long#decode decode}
1242      * and a {@code Long} object representing this value is returned.
1243      *
1244      * <p>The second argument is the default value. A {@code Long} object
1245      * that represents the value of the second argument is returned if there
1246      * is no property of the specified name, if the property does not have
1247      * the correct numeric format, or if the specified name is empty or null.
1248      *
1249      * <p>In other words, this method returns a {@code Long} object equal
1250      * to the value of:
1251      *
1252      * <blockquote>
1253      *  {@code getLong(nm, new Long(val))}
1254      * </blockquote>
1255      *
1256      * but in practice it may be implemented in a manner such as:
1257      *
1258      * <blockquote><pre>
1259      * Long result = getLong(nm, null);
1260      * return (result == null) ? new Long(val) : result;
1261      * </pre></blockquote>
1262      *
1263      * to avoid the unnecessary allocation of a {@code Long} object when
1264      * the default value is not needed.
1265      *
1266      * @param   nm    property name.
1267      * @param   val   default value.
1268      * @return  the {@code Long} value of the property.
1269      * @throws  SecurityException for the same reasons as
1270      *          {@link System#getProperty(String) System.getProperty}
1271      * @see     java.lang.System#getProperty(java.lang.String)
1272      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
1273      */
1274     public static Long getLong(String nm, long val) {
1275         Long result = Long.getLong(nm, null);
1276         return (result == null) ? Long.valueOf(val) : result;
1277     }
1278 
1279     /**
1280      * Returns the {@code long} value of the system property with
1281      * the specified name.  The first argument is treated as the name
1282      * of a system property.  System properties are accessible through
1283      * the {@link java.lang.System#getProperty(java.lang.String)}
1284      * method. The string value of this property is then interpreted
1285      * as a {@code long} value, as per the
1286      * {@link Long#decode decode} method, and a {@code Long} object
1287      * representing this value is returned; in summary:
1288      *
1289      * <ul>
1290      * <li>If the property value begins with the two ASCII characters
1291      * {@code 0x} or the ASCII character {@code #}, not followed by
1292      * a minus sign, then the rest of it is parsed as a hexadecimal integer
1293      * exactly as for the method {@link #valueOf(java.lang.String, int)}
1294      * with radix 16.
1295      * <li>If the property value begins with the ASCII character
1296      * {@code 0} followed by another character, it is parsed as
1297      * an octal integer exactly as by the method {@link
1298      * #valueOf(java.lang.String, int)} with radix 8.
1299      * <li>Otherwise the property value is parsed as a decimal
1300      * integer exactly as by the method
1301      * {@link #valueOf(java.lang.String, int)} with radix 10.
1302      * </ul>
1303      *
1304      * <p>Note that, in every case, neither {@code L}
1305      * ({@code '\u005Cu004C'}) nor {@code l}
1306      * ({@code '\u005Cu006C'}) is permitted to appear at the end
1307      * of the property value as a type indicator, as would be
1308      * permitted in Java programming language source code.
1309      *
1310      * <p>The second argument is the default value. The default value is
1311      * returned if there is no property of the specified name, if the
1312      * property does not have the correct numeric format, or if the
1313      * specified name is empty or {@code null}.
1314      *
1315      * @param   nm   property name.
1316      * @param   val   default value.
1317      * @return  the {@code Long} value of the property.
1318      * @throws  SecurityException for the same reasons as
1319      *          {@link System#getProperty(String) System.getProperty}
1320      * @see     System#getProperty(java.lang.String)
1321      * @see     System#getProperty(java.lang.String, java.lang.String)
1322      */
1323     public static Long getLong(String nm, Long val) {
1324         String v = null;
1325         try {
1326             v = System.getProperty(nm);
1327         } catch (IllegalArgumentException | NullPointerException e) {
1328         }
1329         if (v != null) {
1330             try {
1331                 return Long.decode(v);
1332             } catch (NumberFormatException e) {
1333             }
1334         }
1335         return val;
1336     }
1337 
1338     /**
1339      * Compares two {@code Long} objects numerically.
1340      *
1341      * @param   anotherLong   the {@code Long} to be compared.
1342      * @return  the value {@code 0} if this {@code Long} is
1343      *          equal to the argument {@code Long}; a value less than
1344      *          {@code 0} if this {@code Long} is numerically less
1345      *          than the argument {@code Long}; and a value greater
1346      *          than {@code 0} if this {@code Long} is numerically
1347      *           greater than the argument {@code Long} (signed
1348      *           comparison).
1349      * @since   1.2
1350      */
1351     public int compareTo(Long anotherLong) {
1352         return compare(this.value, anotherLong.value);
1353     }
1354 
1355     /**
1356      * Compares two {@code long} values numerically.
1357      * The value returned is identical to what would be returned by:
1358      * <pre>
1359      *    Long.valueOf(x).compareTo(Long.valueOf(y))
1360      * </pre>
1361      *
1362      * @param  x the first {@code long} to compare
1363      * @param  y the second {@code long} to compare
1364      * @return the value {@code 0} if {@code x == y};
1365      *         a value less than {@code 0} if {@code x < y}; and
1366      *         a value greater than {@code 0} if {@code x > y}
1367      * @since 1.7
1368      */
1369     public static int compare(long x, long y) {
1370         return (x < y) ? -1 : ((x == y) ? 0 : 1);
1371     }
1372 
1373     /**
1374      * Compares two {@code long} values numerically treating the values
1375      * as unsigned.
1376      *
1377      * @param  x the first {@code long} to compare
1378      * @param  y the second {@code long} to compare
1379      * @return the value {@code 0} if {@code x == y}; a value less
1380      *         than {@code 0} if {@code x < y} as unsigned values; and
1381      *         a value greater than {@code 0} if {@code x > y} as
1382      *         unsigned values
1383      * @since 1.8
1384      */
1385     public static int compareUnsigned(long x, long y) {
1386         return compare(x + MIN_VALUE, y + MIN_VALUE);
1387     }
1388 
1389 
1390     /**
1391      * Returns the unsigned quotient of dividing the first argument by
1392      * the second where each argument and the result is interpreted as
1393      * an unsigned value.
1394      *
1395      * <p>Note that in two's complement arithmetic, the three other
1396      * basic arithmetic operations of add, subtract, and multiply are
1397      * bit-wise identical if the two operands are regarded as both
1398      * being signed or both being unsigned.  Therefore separate {@code
1399      * addUnsigned}, etc. methods are not provided.
1400      *
1401      * @param dividend the value to be divided
1402      * @param divisor the value doing the dividing
1403      * @return the unsigned quotient of the first argument divided by
1404      * the second argument
1405      * @see #remainderUnsigned
1406      * @since 1.8
1407      */
1408     public static long divideUnsigned(long dividend, long divisor) {
1409         if (divisor < 0L) { // signed comparison
1410             // Answer must be 0 or 1 depending on relative magnitude
1411             // of dividend and divisor.
1412             return (compareUnsigned(dividend, divisor)) < 0 ? 0L :1L;
1413         }
1414 
1415         if (dividend > 0) //  Both inputs non-negative
1416             return dividend/divisor;
1417         else {
1418             /*
1419              * For simple code, leveraging BigInteger.  Longer and faster
1420              * code written directly in terms of operations on longs is
1421              * possible; see "Hacker's Delight" for divide and remainder
1422              * algorithms.
1423              */
1424             return toUnsignedBigInteger(dividend).
1425                 divide(toUnsignedBigInteger(divisor)).longValue();
1426         }
1427     }
1428 
1429     /**
1430      * Returns the unsigned remainder from dividing the first argument
1431      * by the second where each argument and the result is interpreted
1432      * as an unsigned value.
1433      *
1434      * @param dividend the value to be divided
1435      * @param divisor the value doing the dividing
1436      * @return the unsigned remainder of the first argument divided by
1437      * the second argument
1438      * @see #divideUnsigned
1439      * @since 1.8
1440      */
1441     public static long remainderUnsigned(long dividend, long divisor) {
1442         if (dividend > 0 && divisor > 0) { // signed comparisons
1443             return dividend % divisor;
1444         } else {
1445             if (compareUnsigned(dividend, divisor) < 0) // Avoid explicit check for 0 divisor
1446                 return dividend;
1447             else
1448                 return toUnsignedBigInteger(dividend).
1449                     remainder(toUnsignedBigInteger(divisor)).longValue();
1450         }
1451     }
1452 
1453     // Bit Twiddling
1454 
1455     /**
1456      * The number of bits used to represent a {@code long} value in two's
1457      * complement binary form.
1458      *
1459      * @since 1.5
1460      */
1461     @Native public static final int SIZE = 64;
1462 
1463     /**
1464      * The number of bytes used to represent a {@code long} value in two's
1465      * complement binary form.
1466      *
1467      * @since 1.8
1468      */
1469     public static final int BYTES = SIZE / Byte.SIZE;
1470 
1471     /**
1472      * Returns a {@code long} value with at most a single one-bit, in the
1473      * position of the highest-order ("leftmost") one-bit in the specified
1474      * {@code long} value.  Returns zero if the specified value has no
1475      * one-bits in its two's complement binary representation, that is, if it
1476      * is equal to zero.
1477      *
1478      * @param i the value whose highest one bit is to be computed
1479      * @return a {@code long} value with a single one-bit, in the position
1480      *     of the highest-order one-bit in the specified value, or zero if
1481      *     the specified value is itself equal to zero.
1482      * @since 1.5
1483      */
1484     public static long highestOneBit(long i) {
1485         // HD, Figure 3-1
1486         i |= (i >>  1);
1487         i |= (i >>  2);
1488         i |= (i >>  4);
1489         i |= (i >>  8);
1490         i |= (i >> 16);
1491         i |= (i >> 32);
1492         return i - (i >>> 1);
1493     }
1494 
1495     /**
1496      * Returns a {@code long} value with at most a single one-bit, in the
1497      * position of the lowest-order ("rightmost") one-bit in the specified
1498      * {@code long} value.  Returns zero if the specified value has no
1499      * one-bits in its two's complement binary representation, that is, if it
1500      * is equal to zero.
1501      *
1502      * @param i the value whose lowest one bit is to be computed
1503      * @return a {@code long} value with a single one-bit, in the position
1504      *     of the lowest-order one-bit in the specified value, or zero if
1505      *     the specified value is itself equal to zero.
1506      * @since 1.5
1507      */
1508     public static long lowestOneBit(long i) {
1509         // HD, Section 2-1
1510         return i & -i;
1511     }
1512 
1513     /**
1514      * Returns the number of zero bits preceding the highest-order
1515      * ("leftmost") one-bit in the two's complement binary representation
1516      * of the specified {@code long} value.  Returns 64 if the
1517      * specified value has no one-bits in its two's complement representation,
1518      * in other words if it is equal to zero.
1519      *
1520      * <p>Note that this method is closely related to the logarithm base 2.
1521      * For all positive {@code long} values x:
1522      * <ul>
1523      * <li>floor(log<sub>2</sub>(x)) = {@code 63 - numberOfLeadingZeros(x)}
1524      * <li>ceil(log<sub>2</sub>(x)) = {@code 64 - numberOfLeadingZeros(x - 1)}
1525      * </ul>
1526      *
1527      * @param i the value whose number of leading zeros is to be computed
1528      * @return the number of zero bits preceding the highest-order
1529      *     ("leftmost") one-bit in the two's complement binary representation
1530      *     of the specified {@code long} value, or 64 if the value
1531      *     is equal to zero.
1532      * @since 1.5
1533      */
1534     public static int numberOfLeadingZeros(long i) {
1535         // HD, Figure 5-6
1536          if (i == 0)
1537             return 64;
1538         int n = 1;
1539         int x = (int)(i >>> 32);
1540         if (x == 0) { n += 32; x = (int)i; }
1541         if (x >>> 16 == 0) { n += 16; x <<= 16; }
1542         if (x >>> 24 == 0) { n +=  8; x <<=  8; }
1543         if (x >>> 28 == 0) { n +=  4; x <<=  4; }
1544         if (x >>> 30 == 0) { n +=  2; x <<=  2; }
1545         n -= x >>> 31;
1546         return n;
1547     }
1548 
1549     /**
1550      * Returns the number of zero bits following the lowest-order ("rightmost")
1551      * one-bit in the two's complement binary representation of the specified
1552      * {@code long} value.  Returns 64 if the specified value has no
1553      * one-bits in its two's complement representation, in other words if it is
1554      * equal to zero.
1555      *
1556      * @param i the value whose number of trailing zeros is to be computed
1557      * @return the number of zero bits following the lowest-order ("rightmost")
1558      *     one-bit in the two's complement binary representation of the
1559      *     specified {@code long} value, or 64 if the value is equal
1560      *     to zero.
1561      * @since 1.5
1562      */
1563     public static int numberOfTrailingZeros(long i) {
1564         // HD, Figure 5-14
1565         int x, y;
1566         if (i == 0) return 64;
1567         int n = 63;
1568         y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32);
1569         y = x <<16; if (y != 0) { n = n -16; x = y; }
1570         y = x << 8; if (y != 0) { n = n - 8; x = y; }
1571         y = x << 4; if (y != 0) { n = n - 4; x = y; }
1572         y = x << 2; if (y != 0) { n = n - 2; x = y; }
1573         return n - ((x << 1) >>> 31);
1574     }
1575 
1576     /**
1577      * Returns the number of one-bits in the two's complement binary
1578      * representation of the specified {@code long} value.  This function is
1579      * sometimes referred to as the <i>population count</i>.
1580      *
1581      * @param i the value whose bits are to be counted
1582      * @return the number of one-bits in the two's complement binary
1583      *     representation of the specified {@code long} value.
1584      * @since 1.5
1585      */
1586      public static int bitCount(long i) {
1587         // HD, Figure 5-14
1588         i = i - ((i >>> 1) & 0x5555555555555555L);
1589         i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L);
1590         i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL;
1591         i = i + (i >>> 8);
1592         i = i + (i >>> 16);
1593         i = i + (i >>> 32);
1594         return (int)i & 0x7f;
1595      }
1596 
1597     /**
1598      * Returns the value obtained by rotating the two's complement binary
1599      * representation of the specified {@code long} value left by the
1600      * specified number of bits.  (Bits shifted out of the left hand, or
1601      * high-order, side reenter on the right, or low-order.)
1602      *
1603      * <p>Note that left rotation with a negative distance is equivalent to
1604      * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
1605      * distance)}.  Note also that rotation by any multiple of 64 is a
1606      * no-op, so all but the last six bits of the rotation distance can be
1607      * ignored, even if the distance is negative: {@code rotateLeft(val,
1608      * distance) == rotateLeft(val, distance & 0x3F)}.
1609      *
1610      * @param i the value whose bits are to be rotated left
1611      * @param distance the number of bit positions to rotate left
1612      * @return the value obtained by rotating the two's complement binary
1613      *     representation of the specified {@code long} value left by the
1614      *     specified number of bits.
1615      * @since 1.5
1616      */
1617     public static long rotateLeft(long i, int distance) {
1618         return (i << distance) | (i >>> -distance);
1619     }
1620 
1621     /**
1622      * Returns the value obtained by rotating the two's complement binary
1623      * representation of the specified {@code long} value right by the
1624      * specified number of bits.  (Bits shifted out of the right hand, or
1625      * low-order, side reenter on the left, or high-order.)
1626      *
1627      * <p>Note that right rotation with a negative distance is equivalent to
1628      * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
1629      * distance)}.  Note also that rotation by any multiple of 64 is a
1630      * no-op, so all but the last six bits of the rotation distance can be
1631      * ignored, even if the distance is negative: {@code rotateRight(val,
1632      * distance) == rotateRight(val, distance & 0x3F)}.
1633      *
1634      * @param i the value whose bits are to be rotated right
1635      * @param distance the number of bit positions to rotate right
1636      * @return the value obtained by rotating the two's complement binary
1637      *     representation of the specified {@code long} value right by the
1638      *     specified number of bits.
1639      * @since 1.5
1640      */
1641     public static long rotateRight(long i, int distance) {
1642         return (i >>> distance) | (i << -distance);
1643     }
1644 
1645     /**
1646      * Returns the value obtained by reversing the order of the bits in the
1647      * two's complement binary representation of the specified {@code long}
1648      * value.
1649      *
1650      * @param i the value to be reversed
1651      * @return the value obtained by reversing order of the bits in the
1652      *     specified {@code long} value.
1653      * @since 1.5
1654      */
1655     public static long reverse(long i) {
1656         // HD, Figure 7-1
1657         i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L;
1658         i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L;
1659         i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL;
1660         i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
1661         i = (i << 48) | ((i & 0xffff0000L) << 16) |
1662             ((i >>> 16) & 0xffff0000L) | (i >>> 48);
1663         return i;
1664     }
1665 
1666     /**
1667      * Returns the signum function of the specified {@code long} value.  (The
1668      * return value is -1 if the specified value is negative; 0 if the
1669      * specified value is zero; and 1 if the specified value is positive.)
1670      *
1671      * @param i the value whose signum is to be computed
1672      * @return the signum function of the specified {@code long} value.
1673      * @since 1.5
1674      */
1675     public static int signum(long i) {
1676         // HD, Section 2-7
1677         return (int) ((i >> 63) | (-i >>> 63));
1678     }
1679 
1680     /**
1681      * Returns the value obtained by reversing the order of the bytes in the
1682      * two's complement representation of the specified {@code long} value.
1683      *
1684      * @param i the value whose bytes are to be reversed
1685      * @return the value obtained by reversing the bytes in the specified
1686      *     {@code long} value.
1687      * @since 1.5
1688      */
1689     public static long reverseBytes(long i) {
1690         i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
1691         return (i << 48) | ((i & 0xffff0000L) << 16) |
1692             ((i >>> 16) & 0xffff0000L) | (i >>> 48);
1693     }
1694 
1695     /**
1696      * Adds two {@code long} values together as per the + operator.
1697      *
1698      * @param a the first operand
1699      * @param b the second operand
1700      * @return the sum of {@code a} and {@code b}
1701      * @see java.util.function.BinaryOperator
1702      * @since 1.8
1703      */
1704     public static long sum(long a, long b) {
1705         return a + b;
1706     }
1707 
1708     /**
1709      * Returns the greater of two {@code long} values
1710      * as if by calling {@link Math#max(long, long) Math.max}.
1711      *
1712      * @param a the first operand
1713      * @param b the second operand
1714      * @return the greater of {@code a} and {@code b}
1715      * @see java.util.function.BinaryOperator
1716      * @since 1.8
1717      */
1718     public static long max(long a, long b) {
1719         return Math.max(a, b);
1720     }
1721 
1722     /**
1723      * Returns the smaller of two {@code long} values
1724      * as if by calling {@link Math#min(long, long) Math.min}.
1725      *
1726      * @param a the first operand
1727      * @param b the second operand
1728      * @return the smaller of {@code a} and {@code b}
1729      * @see java.util.function.BinaryOperator
1730      * @since 1.8
1731      */
1732     public static long min(long a, long b) {
1733         return Math.min(a, b);
1734     }
1735 
1736     /** use serialVersionUID from JDK 1.0.2 for interoperability */
1737     @Native private static final long serialVersionUID = 4290774380558885855L;
1738 }