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