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