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