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
 810      * property.  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 {@code
 813      * long} value using the grammar supported by {@link Long#decode decode}
 814      * and a {@code Long} object representing this value is returned.
 815      *
 816      * <p>If there is no property with the specified name, if the
 817      * specified name is empty or {@code null}, or if the property
 818      * does not have the correct numeric format, then {@code null} is
 819      * returned.
 820      *
 821      * <p>In other words, this method returns a {@code Long} object
 822      * equal to the value of:
 823      *
 824      * <blockquote>
 825      *  {@code getLong(nm, null)}
 826      * </blockquote>
 827      *
 828      * @param   nm   property name.
 829      * @return  the {@code Long} value of the property.
 830      * @see     java.lang.System#getProperty(java.lang.String)
 831      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
 832      */
 833     public static Long getLong(String nm) {
 834         return getLong(nm, null);
 835     }
 836 
 837     /**
 838      * Determines the {@code long} value of the system property
 839      * with the specified name.
 840      *
 841      * <p>The first argument is treated as the name of a system
 842      * property.  System properties are accessible through the {@link
 843      * java.lang.System#getProperty(java.lang.String)} method. The
 844      * string value of this property is then interpreted as a {@code
 845      * long} value using the grammar supported by {@link Long#decode decode}
 846      * and a {@code Long} object representing this value is returned.
 847      *
 848      * <p>The second argument is the default value. A {@code Long} object
 849      * that represents the value of the second argument is returned if there
 850      * is no property of the specified name, if the property does not have
 851      * the correct numeric format, or if the specified name is empty or null.
 852      *
 853      * <p>In other words, this method returns a {@code Long} object equal
 854      * to the value of:
 855      *
 856      * <blockquote>
 857      *  {@code getLong(nm, new Long(val))}
 858      * </blockquote>
 859      *
 860      * but in practice it may be implemented in a manner such as:
 861      *
 862      * <blockquote><pre>
 863      * Long result = getLong(nm, null);
 864      * return (result == null) ? new Long(val) : result;
 865      * </pre></blockquote>
 866      *
 867      * to avoid the unnecessary allocation of a {@code Long} object when
 868      * the default value is not needed.
 869      *
 870      * @param   nm    property name.
 871      * @param   val   default value.
 872      * @return  the {@code Long} value of the property.
 873      * @see     java.lang.System#getProperty(java.lang.String)
 874      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
 875      */
 876     public static Long getLong(String nm, long val) {
 877         Long result = Long.getLong(nm, null);
 878         return (result == null) ? Long.valueOf(val) : result;
 879     }
 880 
 881     /**
 882      * Returns the {@code long} value of the system property with
 883      * the specified name.  The first argument is treated as the name
 884      * of a system property.  System properties are accessible through
 885      * the {@link java.lang.System#getProperty(java.lang.String)}
 886      * method. The string value of this property is then interpreted
 887      * as a {@code long} value, as per the
 888      * {@link Long#decode decode} method, and a {@code Long} object
 889      * representing this value is returned; in summary:
 890      *
 891      * <ul>
 892      * <li>If the property value begins with the two ASCII characters
 893      * {@code 0x} or the ASCII character {@code #}, not followed by
 894      * a minus sign, then the rest of it is parsed as a hexadecimal integer
 895      * exactly as for the method {@link #valueOf(java.lang.String, int)}
 896      * with radix 16.
 897      * <li>If the property value begins with the ASCII character
 898      * {@code 0} followed by another character, it is parsed as
 899      * an octal integer exactly as by the method {@link
 900      * #valueOf(java.lang.String, int)} with radix 8.
 901      * <li>Otherwise the property value is parsed as a decimal
 902      * integer exactly as by the method
 903      * {@link #valueOf(java.lang.String, int)} with radix 10.
 904      * </ul>
 905      *
 906      * <p>Note that, in every case, neither {@code L}
 907      * (<code>'&#92;u004C'</code>) nor {@code l}
 908      * (<code>'&#92;u006C'</code>) is permitted to appear at the end
 909      * of the property value as a type indicator, as would be
 910      * permitted in Java programming language source code.
 911      *
 912      * <p>The second argument is the default value. The default value is
 913      * returned if there is no property of the specified name, if the
 914      * property does not have the correct numeric format, or if the
 915      * specified name is empty or {@code null}.
 916      *
 917      * @param   nm   property name.
 918      * @param   val   default value.
 919      * @return  the {@code Long} value of the property.
 920      * @see     System#getProperty(java.lang.String)
 921      * @see     System#getProperty(java.lang.String, java.lang.String)
 922      */
 923     public static Long getLong(String nm, Long val) {
 924         String v = null;
 925         try {
 926             v = System.getProperty(nm);
 927         } catch (IllegalArgumentException | NullPointerException e) {
 928         }
 929         if (v != null) {
 930             try {
 931                 return Long.decode(v);
 932             } catch (NumberFormatException e) {
 933             }
 934         }
 935         return val;
 936     }
 937 
 938     /**
 939      * Compares two {@code Long} objects numerically.
 940      *
 941      * @param   anotherLong   the {@code Long} to be compared.
 942      * @return  the value {@code 0} if this {@code Long} is
 943      *          equal to the argument {@code Long}; a value less than
 944      *          {@code 0} if this {@code Long} is numerically less
 945      *          than the argument {@code Long}; and a value greater
 946      *          than {@code 0} if this {@code Long} is numerically
 947      *           greater than the argument {@code Long} (signed
 948      *           comparison).
 949      * @since   1.2
 950      */
 951     public int compareTo(Long anotherLong) {
 952         return compare(this.value, anotherLong.value);
 953     }
 954 
 955     /**
 956      * Compares two {@code long} values numerically.
 957      * The value returned is identical to what would be returned by:
 958      * <pre>
 959      *    Long.valueOf(x).compareTo(Long.valueOf(y))
 960      * </pre>
 961      *
 962      * @param  x the first {@code long} to compare
 963      * @param  y the second {@code long} to compare
 964      * @return the value {@code 0} if {@code x == y};
 965      *         a value less than {@code 0} if {@code x < y}; and
 966      *         a value greater than {@code 0} if {@code x > y}
 967      * @since 1.7
 968      */
 969     public static int compare(long x, long y) {
 970         return (x < y) ? -1 : ((x == y) ? 0 : 1);
 971     }
 972 
 973 
 974     // Bit Twiddling
 975 
 976     /**
 977      * The number of bits used to represent a {@code long} value in two's
 978      * complement binary form.
 979      *
 980      * @since 1.5
 981      */
 982     public static final int SIZE = 64;
 983 
 984     /**
 985      * Returns a {@code long} value with at most a single one-bit, in the
 986      * position of the highest-order ("leftmost") one-bit in the specified
 987      * {@code long} value.  Returns zero if the specified value has no
 988      * one-bits in its two's complement binary representation, that is, if it
 989      * is equal to zero.
 990      *
 991      * @return a {@code long} value with a single one-bit, in the position
 992      *     of the highest-order one-bit in the specified value, or zero if
 993      *     the specified value is itself equal to zero.
 994      * @since 1.5
 995      */
 996     public static long highestOneBit(long i) {
 997         // HD, Figure 3-1
 998         i |= (i >>  1);
 999         i |= (i >>  2);
1000         i |= (i >>  4);
1001         i |= (i >>  8);
1002         i |= (i >> 16);
1003         i |= (i >> 32);
1004         return i - (i >>> 1);
1005     }
1006 
1007     /**
1008      * Returns a {@code long} value with at most a single one-bit, in the
1009      * position of the lowest-order ("rightmost") one-bit in the specified
1010      * {@code long} value.  Returns zero if the specified value has no
1011      * one-bits in its two's complement binary representation, that is, if it
1012      * is equal to zero.
1013      *
1014      * @return a {@code long} value with a single one-bit, in the position
1015      *     of the lowest-order one-bit in the specified value, or zero if
1016      *     the specified value is itself equal to zero.
1017      * @since 1.5
1018      */
1019     public static long lowestOneBit(long i) {
1020         // HD, Section 2-1
1021         return i & -i;
1022     }
1023 
1024     /**
1025      * Returns the number of zero bits preceding the highest-order
1026      * ("leftmost") one-bit in the two's complement binary representation
1027      * of the specified {@code long} value.  Returns 64 if the
1028      * specified value has no one-bits in its two's complement representation,
1029      * in other words if it is equal to zero.
1030      *
1031      * <p>Note that this method is closely related to the logarithm base 2.
1032      * For all positive {@code long} values x:
1033      * <ul>
1034      * <li>floor(log<sub>2</sub>(x)) = {@code 63 - numberOfLeadingZeros(x)}
1035      * <li>ceil(log<sub>2</sub>(x)) = {@code 64 - numberOfLeadingZeros(x - 1)}
1036      * </ul>
1037      *
1038      * @return the number of zero bits preceding the highest-order
1039      *     ("leftmost") one-bit in the two's complement binary representation
1040      *     of the specified {@code long} value, or 64 if the value
1041      *     is equal to zero.
1042      * @since 1.5
1043      */
1044     public static int numberOfLeadingZeros(long i) {
1045         // HD, Figure 5-6
1046          if (i == 0)
1047             return 64;
1048         int n = 1;
1049         int x = (int)(i >>> 32);
1050         if (x == 0) { n += 32; x = (int)i; }
1051         if (x >>> 16 == 0) { n += 16; x <<= 16; }
1052         if (x >>> 24 == 0) { n +=  8; x <<=  8; }
1053         if (x >>> 28 == 0) { n +=  4; x <<=  4; }
1054         if (x >>> 30 == 0) { n +=  2; x <<=  2; }
1055         n -= x >>> 31;
1056         return n;
1057     }
1058 
1059     /**
1060      * Returns the number of zero bits following the lowest-order ("rightmost")
1061      * one-bit in the two's complement binary representation of the specified
1062      * {@code long} value.  Returns 64 if the specified value has no
1063      * one-bits in its two's complement representation, in other words if it is
1064      * equal to zero.
1065      *
1066      * @return the number of zero bits following the lowest-order ("rightmost")
1067      *     one-bit in the two's complement binary representation of the
1068      *     specified {@code long} value, or 64 if the value is equal
1069      *     to zero.
1070      * @since 1.5
1071      */
1072     public static int numberOfTrailingZeros(long i) {
1073         // HD, Figure 5-14
1074         int x, y;
1075         if (i == 0) return 64;
1076         int n = 63;
1077         y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32);
1078         y = x <<16; if (y != 0) { n = n -16; x = y; }
1079         y = x << 8; if (y != 0) { n = n - 8; x = y; }
1080         y = x << 4; if (y != 0) { n = n - 4; x = y; }
1081         y = x << 2; if (y != 0) { n = n - 2; x = y; }
1082         return n - ((x << 1) >>> 31);
1083     }
1084 
1085     /**
1086      * Returns the number of one-bits in the two's complement binary
1087      * representation of the specified {@code long} value.  This function is
1088      * sometimes referred to as the <i>population count</i>.
1089      *
1090      * @return the number of one-bits in the two's complement binary
1091      *     representation of the specified {@code long} value.
1092      * @since 1.5
1093      */
1094      public static int bitCount(long i) {
1095         // HD, Figure 5-14
1096         i = i - ((i >>> 1) & 0x5555555555555555L);
1097         i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L);
1098         i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL;
1099         i = i + (i >>> 8);
1100         i = i + (i >>> 16);
1101         i = i + (i >>> 32);
1102         return (int)i & 0x7f;
1103      }
1104 
1105     /**
1106      * Returns the value obtained by rotating the two's complement binary
1107      * representation of the specified {@code long} value left by the
1108      * specified number of bits.  (Bits shifted out of the left hand, or
1109      * high-order, side reenter on the right, or low-order.)
1110      *
1111      * <p>Note that left rotation with a negative distance is equivalent to
1112      * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
1113      * distance)}.  Note also that rotation by any multiple of 64 is a
1114      * no-op, so all but the last six bits of the rotation distance can be
1115      * ignored, even if the distance is negative: {@code rotateLeft(val,
1116      * distance) == rotateLeft(val, distance & 0x3F)}.
1117      *
1118      * @return the value obtained by rotating the two's complement binary
1119      *     representation of the specified {@code long} value left by the
1120      *     specified number of bits.
1121      * @since 1.5
1122      */
1123     public static long rotateLeft(long i, int distance) {
1124         return (i << distance) | (i >>> -distance);
1125     }
1126 
1127     /**
1128      * Returns the value obtained by rotating the two's complement binary
1129      * representation of the specified {@code long} value right by the
1130      * specified number of bits.  (Bits shifted out of the right hand, or
1131      * low-order, side reenter on the left, or high-order.)
1132      *
1133      * <p>Note that right rotation with a negative distance is equivalent to
1134      * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
1135      * distance)}.  Note also that rotation by any multiple of 64 is a
1136      * no-op, so all but the last six bits of the rotation distance can be
1137      * ignored, even if the distance is negative: {@code rotateRight(val,
1138      * distance) == rotateRight(val, distance & 0x3F)}.
1139      *
1140      * @return the value obtained by rotating the two's complement binary
1141      *     representation of the specified {@code long} value right by the
1142      *     specified number of bits.
1143      * @since 1.5
1144      */
1145     public static long rotateRight(long i, int distance) {
1146         return (i >>> distance) | (i << -distance);
1147     }
1148 
1149     /**
1150      * Returns the value obtained by reversing the order of the bits in the
1151      * two's complement binary representation of the specified {@code long}
1152      * value.
1153      *
1154      * @return the value obtained by reversing order of the bits in the
1155      *     specified {@code long} value.
1156      * @since 1.5
1157      */
1158     public static long reverse(long i) {
1159         // HD, Figure 7-1
1160         i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L;
1161         i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L;
1162         i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL;
1163         i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
1164         i = (i << 48) | ((i & 0xffff0000L) << 16) |
1165             ((i >>> 16) & 0xffff0000L) | (i >>> 48);
1166         return i;
1167     }
1168 
1169     /**
1170      * Returns the signum function of the specified {@code long} value.  (The
1171      * return value is -1 if the specified value is negative; 0 if the
1172      * specified value is zero; and 1 if the specified value is positive.)
1173      *
1174      * @return the signum function of the specified {@code long} value.
1175      * @since 1.5
1176      */
1177     public static int signum(long i) {
1178         // HD, Section 2-7
1179         return (int) ((i >> 63) | (-i >>> 63));
1180     }
1181 
1182     /**
1183      * Returns the value obtained by reversing the order of the bytes in the
1184      * two's complement representation of the specified {@code long} value.
1185      *
1186      * @return the value obtained by reversing the bytes in the specified
1187      *     {@code long} value.
1188      * @since 1.5
1189      */
1190     public static long reverseBytes(long i) {
1191         i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
1192         return (i << 48) | ((i & 0xffff0000L) << 16) |
1193             ((i >>> 16) & 0xffff0000L) | (i >>> 48);
1194     }
1195 
1196     /** use serialVersionUID from JDK 1.0.2 for interoperability */
1197     private static final long serialVersionUID = 4290774380558885855L;
1198 }