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