码迷,mamicode.com
首页 > 编程语言 > 详细

java.lang.Long 类源码解读

时间:2018-04-06 23:51:13      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:general   tun   util   oat   sar   obj   src   tar   cert   

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

    LongCache的常量池 [-128,127] 有效值。

java.lang.Long 类源码解读

标签:general   tun   util   oat   sar   obj   src   tar   cert   

原文地址:https://www.cnblogs.com/aben-blog/p/8728995.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!