emul/src/main/java/java/lang/Long.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 16 Oct 2012 11:55:56 +0200
changeset 104 1376481f15e7
parent 84 d65b3a2fbfaf
child 179 469199c2994a
permissions -rw-r--r--
Concatenation of strings works
     1 /*
     2  * Copyright (c) 1994, 2009, 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
   707      * {@code byte}.
   708      */
   709     public byte byteValue() {
   710         return (byte)value;
   711     }
   712 
   713     /**
   714      * Returns the value of this {@code Long} as a
   715      * {@code short}.
   716      */
   717     public short shortValue() {
   718         return (short)value;
   719     }
   720 
   721     /**
   722      * Returns the value of this {@code Long} as an
   723      * {@code int}.
   724      */
   725     public int intValue() {
   726         return (int)value;
   727     }
   728 
   729     /**
   730      * Returns the value of this {@code Long} as a
   731      * {@code long} value.
   732      */
   733     public long longValue() {
   734         return (long)value;
   735     }
   736 
   737     /**
   738      * Returns the value of this {@code Long} as a
   739      * {@code float}.
   740      */
   741     public float floatValue() {
   742         return (float)value;
   743     }
   744 
   745     /**
   746      * Returns the value of this {@code Long} as a
   747      * {@code double}.
   748      */
   749     public double doubleValue() {
   750         return (double)value;
   751     }
   752 
   753     /**
   754      * Returns a {@code String} object representing this
   755      * {@code Long}'s value.  The value is converted to signed
   756      * decimal representation and returned as a string, exactly as if
   757      * the {@code long} value were given as an argument to the
   758      * {@link java.lang.Long#toString(long)} method.
   759      *
   760      * @return  a string representation of the value of this object in
   761      *          base&nbsp;10.
   762      */
   763     public String toString() {
   764         return toString(value);
   765     }
   766 
   767     /**
   768      * Returns a hash code for this {@code Long}. The result is
   769      * the exclusive OR of the two halves of the primitive
   770      * {@code long} value held by this {@code Long}
   771      * object. That is, the hashcode is the value of the expression:
   772      *
   773      * <blockquote>
   774      *  {@code (int)(this.longValue()^(this.longValue()>>>32))}
   775      * </blockquote>
   776      *
   777      * @return  a hash code value for this object.
   778      */
   779     public int hashCode() {
   780         return (int)(value ^ (value >>> 32));
   781     }
   782 
   783     /**
   784      * Compares this object to the specified object.  The result is
   785      * {@code true} if and only if the argument is not
   786      * {@code null} and is a {@code Long} object that
   787      * contains the same {@code long} value as this object.
   788      *
   789      * @param   obj   the object to compare with.
   790      * @return  {@code true} if the objects are the same;
   791      *          {@code false} otherwise.
   792      */
   793     public boolean equals(Object obj) {
   794         if (obj instanceof Long) {
   795             return value == ((Long)obj).longValue();
   796         }
   797         return false;
   798     }
   799 
   800     /**
   801      * Determines the {@code long} value of the system property
   802      * with the specified name.
   803      *
   804      * <p>The first argument is treated as the name of a system property.
   805      * System properties are accessible through the {@link
   806      * java.lang.System#getProperty(java.lang.String)} method. The
   807      * string value of this property is then interpreted as a
   808      * {@code long} value and a {@code Long} object
   809      * representing this value is returned.  Details of possible
   810      * numeric formats can be found with the definition of
   811      * {@code getProperty}.
   812      *
   813      * <p>If there is no property with the specified name, if the
   814      * specified name is empty or {@code null}, or if the
   815      * property does not have the correct numeric format, then
   816      * {@code null} is returned.
   817      *
   818      * <p>In other words, this method returns a {@code Long} object equal to
   819      * the value of:
   820      *
   821      * <blockquote>
   822      *  {@code getLong(nm, null)}
   823      * </blockquote>
   824      *
   825      * @param   nm   property name.
   826      * @return  the {@code Long} value of the property.
   827      * @see     java.lang.System#getProperty(java.lang.String)
   828      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
   829      */
   830     public static Long getLong(String nm) {
   831         return getLong(nm, null);
   832     }
   833 
   834     /**
   835      * Determines the {@code long} value of the system property
   836      * with the specified name.
   837      *
   838      * <p>The first argument is treated as the name of a system property.
   839      * System properties are accessible through the {@link
   840      * java.lang.System#getProperty(java.lang.String)} method. The
   841      * string value of this property is then interpreted as a
   842      * {@code long} value and a {@code Long} object
   843      * representing this value is returned.  Details of possible
   844      * numeric formats can be found with the definition of
   845      * {@code getProperty}.
   846      *
   847      * <p>The second argument is the default value. A {@code Long} object
   848      * that represents the value of the second argument is returned if there
   849      * is no property of the specified name, if the property does not have
   850      * the correct numeric format, or if the specified name is empty or null.
   851      *
   852      * <p>In other words, this method returns a {@code Long} object equal
   853      * to the value of:
   854      *
   855      * <blockquote>
   856      *  {@code getLong(nm, new Long(val))}
   857      * </blockquote>
   858      *
   859      * but in practice it may be implemented in a manner such as:
   860      *
   861      * <blockquote><pre>
   862      * Long result = getLong(nm, null);
   863      * return (result == null) ? new Long(val) : result;
   864      * </pre></blockquote>
   865      *
   866      * to avoid the unnecessary allocation of a {@code Long} object when
   867      * the default value is not needed.
   868      *
   869      * @param   nm    property name.
   870      * @param   val   default value.
   871      * @return  the {@code Long} value of the property.
   872      * @see     java.lang.System#getProperty(java.lang.String)
   873      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
   874      */
   875     public static Long getLong(String nm, long val) {
   876         Long result = Long.getLong(nm, null);
   877         return (result == null) ? Long.valueOf(val) : result;
   878     }
   879 
   880     /**
   881      * Returns the {@code long} value of the system property with
   882      * the specified name.  The first argument is treated as the name
   883      * of a system property.  System properties are accessible through
   884      * the {@link java.lang.System#getProperty(java.lang.String)}
   885      * method. The string value of this property is then interpreted
   886      * as a {@code long} value, as per the
   887      * {@code Long.decode} method, and a {@code Long} object
   888      * representing this value is returned.
   889      *
   890      * <ul>
   891      * <li>If the property value begins with the two ASCII characters
   892      * {@code 0x} or the ASCII character {@code #}, not followed by
   893      * a minus sign, then the rest of it is parsed as a hexadecimal integer
   894      * exactly as for the method {@link #valueOf(java.lang.String, int)}
   895      * with radix 16.
   896      * <li>If the property value begins with the ASCII character
   897      * {@code 0} followed by another character, it is parsed as
   898      * an octal integer exactly as by the method {@link
   899      * #valueOf(java.lang.String, int)} with radix 8.
   900      * <li>Otherwise the property value is parsed as a decimal
   901      * integer exactly as by the method
   902      * {@link #valueOf(java.lang.String, int)} with radix 10.
   903      * </ul>
   904      *
   905      * <p>Note that, in every case, neither {@code L}
   906      * (<code>'&#92;u004C'</code>) nor {@code l}
   907      * (<code>'&#92;u006C'</code>) is permitted to appear at the end
   908      * of the property value as a type indicator, as would be
   909      * permitted in Java programming language source code.
   910      *
   911      * <p>The second argument is the default value. The default value is
   912      * returned if there is no property of the specified name, if the
   913      * property does not have the correct numeric format, or if the
   914      * specified name is empty or {@code null}.
   915      *
   916      * @param   nm   property name.
   917      * @param   val   default value.
   918      * @return  the {@code Long} value of the property.
   919      * @see     java.lang.System#getProperty(java.lang.String)
   920      * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
   921      * @see java.lang.Long#decode
   922      */
   923     public static Long getLong(String nm, Long val) {
   924         String v = null;
   925         try {
   926             v = AbstractStringBuilder.getProperty(nm);
   927         } catch (IllegalArgumentException e) {
   928         } catch (NullPointerException e) {
   929         }
   930         if (v != null) {
   931             try {
   932                 return Long.decode(v);
   933             } catch (NumberFormatException e) {
   934             }
   935         }
   936         return val;
   937     }
   938 
   939     /**
   940      * Compares two {@code Long} objects numerically.
   941      *
   942      * @param   anotherLong   the {@code Long} to be compared.
   943      * @return  the value {@code 0} if this {@code Long} is
   944      *          equal to the argument {@code Long}; a value less than
   945      *          {@code 0} if this {@code Long} is numerically less
   946      *          than the argument {@code Long}; and a value greater
   947      *          than {@code 0} if this {@code Long} is numerically
   948      *           greater than the argument {@code Long} (signed
   949      *           comparison).
   950      * @since   1.2
   951      */
   952     public int compareTo(Long anotherLong) {
   953         return compare(this.value, anotherLong.value);
   954     }
   955 
   956     /**
   957      * Compares two {@code long} values numerically.
   958      * The value returned is identical to what would be returned by:
   959      * <pre>
   960      *    Long.valueOf(x).compareTo(Long.valueOf(y))
   961      * </pre>
   962      *
   963      * @param  x the first {@code long} to compare
   964      * @param  y the second {@code long} to compare
   965      * @return the value {@code 0} if {@code x == y};
   966      *         a value less than {@code 0} if {@code x < y}; and
   967      *         a value greater than {@code 0} if {@code x > y}
   968      * @since 1.7
   969      */
   970     public static int compare(long x, long y) {
   971         return (x < y) ? -1 : ((x == y) ? 0 : 1);
   972     }
   973 
   974 
   975     // Bit Twiddling
   976 
   977     /**
   978      * The number of bits used to represent a {@code long} value in two's
   979      * complement binary form.
   980      *
   981      * @since 1.5
   982      */
   983     public static final int SIZE = 64;
   984 
   985     /**
   986      * Returns a {@code long} value with at most a single one-bit, in the
   987      * position of the highest-order ("leftmost") one-bit in the specified
   988      * {@code long} value.  Returns zero if the specified value has no
   989      * one-bits in its two's complement binary representation, that is, if it
   990      * is equal to zero.
   991      *
   992      * @return a {@code long} value with a single one-bit, in the position
   993      *     of the highest-order one-bit in the specified value, or zero if
   994      *     the specified value is itself equal to zero.
   995      * @since 1.5
   996      */
   997     public static long highestOneBit(long i) {
   998         // HD, Figure 3-1
   999         i |= (i >>  1);
  1000         i |= (i >>  2);
  1001         i |= (i >>  4);
  1002         i |= (i >>  8);
  1003         i |= (i >> 16);
  1004         i |= (i >> 32);
  1005         return i - (i >>> 1);
  1006     }
  1007 
  1008     /**
  1009      * Returns a {@code long} value with at most a single one-bit, in the
  1010      * position of the lowest-order ("rightmost") one-bit in the specified
  1011      * {@code long} value.  Returns zero if the specified value has no
  1012      * one-bits in its two's complement binary representation, that is, if it
  1013      * is equal to zero.
  1014      *
  1015      * @return a {@code long} value with a single one-bit, in the position
  1016      *     of the lowest-order one-bit in the specified value, or zero if
  1017      *     the specified value is itself equal to zero.
  1018      * @since 1.5
  1019      */
  1020     public static long lowestOneBit(long i) {
  1021         // HD, Section 2-1
  1022         return i & -i;
  1023     }
  1024 
  1025     /**
  1026      * Returns the number of zero bits preceding the highest-order
  1027      * ("leftmost") one-bit in the two's complement binary representation
  1028      * of the specified {@code long} value.  Returns 64 if the
  1029      * specified value has no one-bits in its two's complement representation,
  1030      * in other words if it is equal to zero.
  1031      *
  1032      * <p>Note that this method is closely related to the logarithm base 2.
  1033      * For all positive {@code long} values x:
  1034      * <ul>
  1035      * <li>floor(log<sub>2</sub>(x)) = {@code 63 - numberOfLeadingZeros(x)}
  1036      * <li>ceil(log<sub>2</sub>(x)) = {@code 64 - numberOfLeadingZeros(x - 1)}
  1037      * </ul>
  1038      *
  1039      * @return the number of zero bits preceding the highest-order
  1040      *     ("leftmost") one-bit in the two's complement binary representation
  1041      *     of the specified {@code long} value, or 64 if the value
  1042      *     is equal to zero.
  1043      * @since 1.5
  1044      */
  1045     public static int numberOfLeadingZeros(long i) {
  1046         // HD, Figure 5-6
  1047          if (i == 0)
  1048             return 64;
  1049         int n = 1;
  1050         int x = (int)(i >>> 32);
  1051         if (x == 0) { n += 32; x = (int)i; }
  1052         if (x >>> 16 == 0) { n += 16; x <<= 16; }
  1053         if (x >>> 24 == 0) { n +=  8; x <<=  8; }
  1054         if (x >>> 28 == 0) { n +=  4; x <<=  4; }
  1055         if (x >>> 30 == 0) { n +=  2; x <<=  2; }
  1056         n -= x >>> 31;
  1057         return n;
  1058     }
  1059 
  1060     /**
  1061      * Returns the number of zero bits following the lowest-order ("rightmost")
  1062      * one-bit in the two's complement binary representation of the specified
  1063      * {@code long} value.  Returns 64 if the specified value has no
  1064      * one-bits in its two's complement representation, in other words if it is
  1065      * equal to zero.
  1066      *
  1067      * @return the number of zero bits following the lowest-order ("rightmost")
  1068      *     one-bit in the two's complement binary representation of the
  1069      *     specified {@code long} value, or 64 if the value is equal
  1070      *     to zero.
  1071      * @since 1.5
  1072      */
  1073     public static int numberOfTrailingZeros(long i) {
  1074         // HD, Figure 5-14
  1075         int x, y;
  1076         if (i == 0) return 64;
  1077         int n = 63;
  1078         y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32);
  1079         y = x <<16; if (y != 0) { n = n -16; x = y; }
  1080         y = x << 8; if (y != 0) { n = n - 8; x = y; }
  1081         y = x << 4; if (y != 0) { n = n - 4; x = y; }
  1082         y = x << 2; if (y != 0) { n = n - 2; x = y; }
  1083         return n - ((x << 1) >>> 31);
  1084     }
  1085 
  1086     /**
  1087      * Returns the number of one-bits in the two's complement binary
  1088      * representation of the specified {@code long} value.  This function is
  1089      * sometimes referred to as the <i>population count</i>.
  1090      *
  1091      * @return the number of one-bits in the two's complement binary
  1092      *     representation of the specified {@code long} value.
  1093      * @since 1.5
  1094      */
  1095      public static int bitCount(long i) {
  1096         // HD, Figure 5-14
  1097         i = i - ((i >>> 1) & 0x5555555555555555L);
  1098         i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L);
  1099         i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL;
  1100         i = i + (i >>> 8);
  1101         i = i + (i >>> 16);
  1102         i = i + (i >>> 32);
  1103         return (int)i & 0x7f;
  1104      }
  1105 
  1106     /**
  1107      * Returns the value obtained by rotating the two's complement binary
  1108      * representation of the specified {@code long} value left by the
  1109      * specified number of bits.  (Bits shifted out of the left hand, or
  1110      * high-order, side reenter on the right, or low-order.)
  1111      *
  1112      * <p>Note that left rotation with a negative distance is equivalent to
  1113      * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
  1114      * distance)}.  Note also that rotation by any multiple of 64 is a
  1115      * no-op, so all but the last six bits of the rotation distance can be
  1116      * ignored, even if the distance is negative: {@code rotateLeft(val,
  1117      * distance) == rotateLeft(val, distance & 0x3F)}.
  1118      *
  1119      * @return the value obtained by rotating the two's complement binary
  1120      *     representation of the specified {@code long} value left by the
  1121      *     specified number of bits.
  1122      * @since 1.5
  1123      */
  1124     public static long rotateLeft(long i, int distance) {
  1125         return (i << distance) | (i >>> -distance);
  1126     }
  1127 
  1128     /**
  1129      * Returns the value obtained by rotating the two's complement binary
  1130      * representation of the specified {@code long} value right by the
  1131      * specified number of bits.  (Bits shifted out of the right hand, or
  1132      * low-order, side reenter on the left, or high-order.)
  1133      *
  1134      * <p>Note that right rotation with a negative distance is equivalent to
  1135      * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
  1136      * distance)}.  Note also that rotation by any multiple of 64 is a
  1137      * no-op, so all but the last six bits of the rotation distance can be
  1138      * ignored, even if the distance is negative: {@code rotateRight(val,
  1139      * distance) == rotateRight(val, distance & 0x3F)}.
  1140      *
  1141      * @return the value obtained by rotating the two's complement binary
  1142      *     representation of the specified {@code long} value right by the
  1143      *     specified number of bits.
  1144      * @since 1.5
  1145      */
  1146     public static long rotateRight(long i, int distance) {
  1147         return (i >>> distance) | (i << -distance);
  1148     }
  1149 
  1150     /**
  1151      * Returns the value obtained by reversing the order of the bits in the
  1152      * two's complement binary representation of the specified {@code long}
  1153      * value.
  1154      *
  1155      * @return the value obtained by reversing order of the bits in the
  1156      *     specified {@code long} value.
  1157      * @since 1.5
  1158      */
  1159     public static long reverse(long i) {
  1160         // HD, Figure 7-1
  1161         i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L;
  1162         i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L;
  1163         i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL;
  1164         i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
  1165         i = (i << 48) | ((i & 0xffff0000L) << 16) |
  1166             ((i >>> 16) & 0xffff0000L) | (i >>> 48);
  1167         return i;
  1168     }
  1169 
  1170     /**
  1171      * Returns the signum function of the specified {@code long} value.  (The
  1172      * return value is -1 if the specified value is negative; 0 if the
  1173      * specified value is zero; and 1 if the specified value is positive.)
  1174      *
  1175      * @return the signum function of the specified {@code long} value.
  1176      * @since 1.5
  1177      */
  1178     public static int signum(long i) {
  1179         // HD, Section 2-7
  1180         return (int) ((i >> 63) | (-i >>> 63));
  1181     }
  1182 
  1183     /**
  1184      * Returns the value obtained by reversing the order of the bytes in the
  1185      * two's complement representation of the specified {@code long} value.
  1186      *
  1187      * @return the value obtained by reversing the bytes in the specified
  1188      *     {@code long} value.
  1189      * @since 1.5
  1190      */
  1191     public static long reverseBytes(long i) {
  1192         i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
  1193         return (i << 48) | ((i & 0xffff0000L) << 16) |
  1194             ((i >>> 16) & 0xffff0000L) | (i >>> 48);
  1195     }
  1196 
  1197     /** use serialVersionUID from JDK 1.0.2 for interoperability */
  1198     private static final long serialVersionUID = 4290774380558885855L;
  1199 }