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