KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > lang > Long


1 /*
2  * @(#)Long.java 1.79 04/05/11
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.lang;
9
10 /**
11  * The <code>Long</code> class wraps a value of the primitive type
12  * <code>long</code> in an object. An object of type <code>Long</code>
13  * contains a single field whose type is <code>long</code>.
14  *
15  * <p>
16  *
17  * In addition, this class provides several methods for converting a
18  * <code>long</code> to a <code>String</code> and a
19  * <code>String</code> to a <code>long</code>, as well as other
20  * constants and methods useful when dealing with a <code>long</code>.
21  *
22  * <p>Implementation note: The implementations of the "bit twiddling"
23  * methods (such as {@link #highestOneBit(long) highestOneBit} and
24  * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are
25  * based on material from Henry S. Warren, Jr.'s <i>Hacker's
26  * Delight</i>, (Addison Wesley, 2002).
27  *
28  * @author Lee Boynton
29  * @author Arthur van Hoff
30  * @author Josh Bloch
31  * @version 1.79, 05/11/04
32  * @since JDK1.0
33  */

34 public final class Long extends Number JavaDoc implements Comparable JavaDoc<Long JavaDoc> {
35     /**
36      * A constant holding the minimum value a <code>long</code> can
37      * have, -2<sup>63</sup>.
38      */

39     public static final long MIN_VALUE = 0x8000000000000000L;
40
41     /**
42      * A constant holding the maximum value a <code>long</code> can
43      * have, 2<sup>63</sup>-1.
44      */

45     public static final long MAX_VALUE = 0x7fffffffffffffffL;
46
47     /**
48      * The <code>Class</code> instance representing the primitive type
49      * <code>long</code>.
50      *
51      * @since JDK1.1
52      */

53     public static final Class JavaDoc<Long JavaDoc> TYPE = (Class JavaDoc<Long JavaDoc>) Class.getPrimitiveClass("long");
54
55     /**
56      * Returns a string representation of the first argument in the
57      * radix specified by the second argument.
58      * <p>
59      * If the radix is smaller than <code>Character.MIN_RADIX</code>
60      * or larger than <code>Character.MAX_RADIX</code>, then the radix
61      * <code>10</code> is used instead.
62      * <p>
63      * If the first argument is negative, the first element of the
64      * result is the ASCII minus sign <code>'-'</code>
65      * (<code>'&#92;u002d'</code>). If the first argument is not
66      * negative, no sign character appears in the result.
67      * <p>
68      * The remaining characters of the result represent the magnitude
69      * of the first argument. If the magnitude is zero, it is
70      * represented by a single zero character <code>'0'</code>
71      * (<code>'&#92;u0030'</code>); otherwise, the first character of
72      * the representation of the magnitude will not be the zero
73      * character. The following ASCII characters are used as digits:
74      * <blockquote><pre>
75      * 0123456789abcdefghijklmnopqrstuvwxyz
76      * </pre></blockquote>
77      * These are <code>'&#92;u0030'</code> through
78      * <code>'&#92;u0039'</code> and <code>'&#92;u0061'</code> through
79      * <code>'&#92;u007a'</code>. If <code>radix</code> is
80      * <var>N</var>, then the first <var>N</var> of these characters
81      * are used as radix-<var>N</var> digits in the order shown. Thus,
82      * the digits for hexadecimal (radix 16) are
83      * <code>0123456789abcdef</code>. If uppercase letters are
84      * desired, the {@link java.lang.String#toUpperCase()} method may
85      * be called on the result:
86      * <blockquote><pre>
87      * Long.toString(n, 16).toUpperCase()
88      * </pre></blockquote>
89      *
90      * @param i a <code>long</code>to be converted to a string.
91      * @param radix the radix to use in the string representation.
92      * @return a string representation of the argument in the specified radix.
93      * @see java.lang.Character#MAX_RADIX
94      * @see java.lang.Character#MIN_RADIX
95      */

96     public static String JavaDoc toString(long i, int radix) {
97         if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
98         radix = 10;
99         if (radix == 10)
100             return toString(i);
101         char[] buf = new char[65];
102         int charPos = 64;
103         boolean negative = (i < 0);
104
105         if (!negative) {
106             i = -i;
107         }
108
109         while (i <= -radix) {
110             buf[charPos--] = Integer.digits[(int)(-(i % radix))];
111             i = i / radix;
112         }
113         buf[charPos] = Integer.digits[(int)(-i)];
114
115         if (negative) {
116             buf[--charPos] = '-';
117         }
118
119         return new String JavaDoc(buf, charPos, (65 - charPos));
120     }
121
122     /**
123      * Returns a string representation of the <code>long</code>
124      * argument as an unsigned integer in base&nbsp;16.
125      * <p>
126      * The unsigned <code>long</code> value is the argument plus
127      * 2<sup>64</sup> if the argument is negative; otherwise, it is
128      * equal to the argument. This value is converted to a string of
129      * ASCII digits in hexadecimal (base&nbsp;16) with no extra
130      * leading <code>0</code>s. If the unsigned magnitude is zero, it
131      * is represented by a single zero character <code>'0'</code>
132      * (<code>'&#92;u0030'</code>); otherwise, the first character of
133      * the representation of the unsigned magnitude will not be the
134      * zero character. The following characters are used as
135      * hexadecimal digits:
136      * <blockquote><pre>
137      * 0123456789abcdef
138      * </pre></blockquote>
139      * These are the characters <code>'&#92;u0030'</code> through
140      * <code>'&#92;u0039'</code> and <code>'&#92;u0061'</code> through
141      * <code>'&#92;u0066'</code>. If uppercase letters are desired,
142      * the {@link java.lang.String#toUpperCase()} method may be called
143      * on the result:
144      * <blockquote><pre>
145      * Long.toHexString(n).toUpperCase()
146      * </pre></blockquote>
147      *
148      * @param i a <code>long</code> to be converted to a string.
149      * @return the string representation of the unsigned <code>long</code>
150      * value represented by the argument in hexadecimal
151      * (base&nbsp;16).
152      * @since JDK 1.0.2
153      */

154     public static String JavaDoc toHexString(long i) {
155     return toUnsignedString(i, 4);
156     }
157
158     /**
159      * Returns a string representation of the <code>long</code>
160      * argument as an unsigned integer in base&nbsp;8.
161      * <p>
162      * The unsigned <code>long</code> value is the argument plus
163      * 2<sup>64</sup> if the argument is negative; otherwise, it is
164      * equal to the argument. This value is converted to a string of
165      * ASCII digits in octal (base&nbsp;8) with no extra leading
166      * <code>0</code>s.
167      * <p>
168      * If the unsigned magnitude is zero, it is represented by a
169      * single zero character <code>'0'</code>
170      * (<code>'&#92;u0030'</code>); otherwise, the first character of
171      * the representation of the unsigned magnitude will not be the
172      * zero character. The following characters are used as octal
173      * digits:
174      * <blockquote><pre>
175      * 01234567
176      * </pre></blockquote>
177      * These are the characters <code>'&#92;u0030'</code> through
178      * <code>'&#92;u0037'</code>.
179      *
180      * @param i a <code>long</code> to be converted to a string.
181      * @return the string representation of the unsigned <code>long</code>
182      * value represented by the argument in octal (base&nbsp;8).
183      * @since JDK 1.0.2
184      */

185     public static String JavaDoc toOctalString(long i) {
186     return toUnsignedString(i, 3);
187     }
188
189     /**
190      * Returns a string representation of the <code>long</code>
191      * argument as an unsigned integer in base&nbsp;2.
192      * <p>
193      * The unsigned <code>long</code> value is the argument plus
194      * 2<sup>64</sup> if the argument is negative; otherwise, it is
195      * equal to the argument. This value is converted to a string of
196      * ASCII digits in binary (base&nbsp;2) with no extra leading
197      * <code>0</code>s. If the unsigned magnitude is zero, it is
198      * represented by a single zero character <code>'0'</code>
199      * (<code>'&#92;u0030'</code>); otherwise, the first character of
200      * the representation of the unsigned magnitude will not be the
201      * zero character. The characters <code>'0'</code>
202      * (<code>'&#92;u0030'</code>) and <code>'1'</code>
203      * (<code>'&#92;u0031'</code>) are used as binary digits.
204      *
205      * @param i a <code>long</code> to be converted to a string.
206      * @return the string representation of the unsigned <code>long</code>
207      * value represented by the argument in binary (base&nbsp;2).
208      * @since JDK 1.0.2
209      */

210     public static String JavaDoc toBinaryString(long i) {
211     return toUnsignedString(i, 1);
212     }
213
214     /**
215      * Convert the integer to an unsigned number.
216      */

217     private static String JavaDoc toUnsignedString(long i, int shift) {
218     char[] buf = new char[64];
219     int charPos = 64;
220     int radix = 1 << shift;
221     long mask = radix - 1;
222     do {
223         buf[--charPos] = Integer.digits[(int)(i & mask)];
224         i >>>= shift;
225     } while (i != 0);
226     return new String JavaDoc(buf, charPos, (64 - charPos));
227     }
228
229     /**
230      * Returns a <code>String</code> object representing the specified
231      * <code>long</code>. The argument is converted to signed decimal
232      * representation and returned as a string, exactly as if the
233      * argument and the radix 10 were given as arguments to the {@link
234      * #toString(long, int)} method.
235      *
236      * @param i a <code>long</code> to be converted.
237      * @return a string representation of the argument in base&nbsp;10.
238      */

239     public static String JavaDoc toString(long i) {
240         if (i == Long.MIN_VALUE)
241             return "-9223372036854775808";
242         int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
243         char[] buf = new char[size];
244         getChars(i, size, buf);
245         return new String JavaDoc(0, size, buf);
246     }
247
248     /**
249      * Places characters representing the integer i into the
250      * character array buf. The characters are placed into
251      * the buffer backwards starting with the least significant
252      * digit at the specified index (exclusive), and working
253      * backwards from there.
254      *
255      * Will fail if i == Long.MIN_VALUE
256      */

257     static void getChars(long i, int index, char[] buf) {
258         long q;
259         int r;
260         int charPos = index;
261         char sign = 0;
262
263         if (i < 0) {
264             sign = '-';
265             i = -i;
266         }
267
268         // Get 2 digits/iteration using longs until quotient fits into an int
269
while (i > Integer.MAX_VALUE) {
270             q = i / 100;
271             // really: r = i - (q * 100);
272
r = (int)(i - ((q << 6) + (q << 5) + (q << 2)));
273             i = q;
274             buf[--charPos] = Integer.DigitOnes[r];
275             buf[--charPos] = Integer.DigitTens[r];
276         }
277
278         // Get 2 digits/iteration using ints
279
int q2;
280         int i2 = (int)i;
281         while (i2 >= 65536) {
282             q2 = i2 / 100;
283             // really: r = i2 - (q * 100);
284
r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
285             i2 = q2;
286             buf[--charPos] = Integer.DigitOnes[r];
287             buf[--charPos] = Integer.DigitTens[r];
288         }
289
290         // Fall thru to fast mode for smaller numbers
291
// assert(i2 <= 65536, i2);
292
for (;;) {
293             q2 = (i2 * 52429) >>> (16+3);
294             r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ...
295
buf[--charPos] = Integer.digits[r];
296             i2 = q2;
297             if (i2 == 0) break;
298         }
299         if (sign != 0) {
300             buf[--charPos] = sign;
301         }
302     }
303
304     // Requires positive x
305
static int stringSize(long x) {
306         long p = 10;
307         for (int i=1; i<19; i++) {
308             if (x < p)
309                 return i;
310             p = 10*p;
311         }
312         return 19;
313     }
314
315     /**
316      * Parses the string argument as a signed <code>long</code> in the
317      * radix specified by the second argument. The characters in the
318      * string must all be digits of the specified radix (as determined
319      * by whether {@link java.lang.Character#digit(char, int)} returns
320      * a nonnegative value), except that the first character may be an
321      * ASCII minus sign <code>'-'</code> (<code>'&#92;u002D'</code>) to
322      * indicate a negative value. The resulting <code>long</code>
323      * value is returned.
324      * <p>
325      * Note that neither the character <code>L</code>
326      * (<code>'&#92;u004C'</code>) nor <code>l</code>
327      * (<code>'&#92;u006C'</code>) is permitted to appear at the end
328      * of the string as a type indicator, as would be permitted in
329      * Java programming language source code - except that either
330      * <code>L</code> or <code>l</code> may appear as a digit for a
331      * radix greater than 22.
332      * <p>
333      * An exception of type <code>NumberFormatException</code> is
334      * thrown if any of the following situations occurs:
335      * <ul>
336      * <li>The first argument is <code>null</code> or is a string of
337      * length zero.
338      * <li>The <code>radix</code> is either smaller than {@link
339      * java.lang.Character#MIN_RADIX} or larger than {@link
340      * java.lang.Character#MAX_RADIX}.
341      * <li>Any character of the string is not a digit of the specified
342      * radix, except that the first character may be a minus sign
343      * <code>'-'</code> (<code>'&#92;u002d'</code>) provided that the
344      * string is longer than length 1.
345      * <li>The value represented by the string is not a value of type
346      * <code>long</code>.
347      * </ul><p>
348      * Examples:
349      * <blockquote><pre>
350      * parseLong("0", 10) returns 0L
351      * parseLong("473", 10) returns 473L
352      * parseLong("-0", 10) returns 0L
353      * parseLong("-FF", 16) returns -255L
354      * parseLong("1100110", 2) returns 102L
355      * parseLong("99", 8) throws a NumberFormatException
356      * parseLong("Hazelnut", 10) throws a NumberFormatException
357      * parseLong("Hazelnut", 36) returns 1356099454469L
358      * </pre></blockquote>
359      *
360      * @param s the <code>String</code> containing the
361      * <code>long</code> representation to be parsed.
362      * @param radix the radix to be used while parsing <code>s</code>.
363      * @return the <code>long</code> represented by the string argument in
364      * the specified radix.
365      * @exception NumberFormatException if the string does not contain a
366      * parsable <code>long</code>.
367      */

368     public static long parseLong(String JavaDoc s, int radix)
369               throws NumberFormatException JavaDoc
370     {
371         if (s == null) {
372             throw new NumberFormatException JavaDoc("null");
373         }
374
375     if (radix < Character.MIN_RADIX) {
376         throw new NumberFormatException JavaDoc("radix " + radix +
377                         " less than Character.MIN_RADIX");
378     }
379     if (radix > Character.MAX_RADIX) {
380         throw new NumberFormatException JavaDoc("radix " + radix +
381                         " greater than Character.MAX_RADIX");
382     }
383
384     long result = 0;
385     boolean negative = false;
386     int i = 0, max = s.length();
387     long limit;
388     long multmin;
389     int digit;
390
391     if (max > 0) {
392         if (s.charAt(0) == '-') {
393         negative = true;
394         limit = Long.MIN_VALUE;
395         i++;
396         } else {
397         limit = -Long.MAX_VALUE;
398         }
399         multmin = limit / radix;
400             if (i < max) {
401                 digit = Character.digit(s.charAt(i++),radix);
402         if (digit < 0) {
403             throw NumberFormatException.forInputString(s);
404         } else {
405             result = -digit;
406         }
407         }
408         while (i < max) {
409         // Accumulating negatively avoids surprises near MAX_VALUE
410
digit = Character.digit(s.charAt(i++),radix);
411         if (digit < 0) {
412             throw NumberFormatException.forInputString(s);
413         }
414         if (result < multmin) {
415             throw NumberFormatException.forInputString(s);
416         }
417         result *= radix;
418         if (result < limit + digit) {
419             throw NumberFormatException.forInputString(s);
420         }
421         result -= digit;
422         }
423     } else {
424         throw NumberFormatException.forInputString(s);
425     }
426     if (negative) {
427         if (i > 1) {
428         return result;
429         } else { /* Only got "-" */
430         throw NumberFormatException.forInputString(s);
431         }
432     } else {
433         return -result;
434     }
435     }
436
437     /**
438      * Parses the string argument as a signed decimal
439      * <code>long</code>. The characters in the string must all be
440      * decimal digits, except that the first character may be an ASCII
441      * minus sign <code>'-'</code> (<code>&#92;u002D'</code>) to
442      * indicate a negative value. The resulting <code>long</code>
443      * value is returned, exactly as if the argument and the radix
444      * <code>10</code> were given as arguments to the {@link
445      * #parseLong(java.lang.String, int)} method.
446      * <p>
447      * Note that neither the character <code>L</code>
448      * (<code>'&#92;u004C'</code>) nor <code>l</code>
449      * (<code>'&#92;u006C'</code>) is permitted to appear at the end
450      * of the string as a type indicator, as would be permitted in
451      * Java programming language source code.
452      *
453      * @param s a <code>String</code> containing the <code>long</code>
454      * representation to be parsed
455      * @return the <code>long</code> represented by the argument in
456      * decimal.
457      * @exception NumberFormatException if the string does not contain a
458      * parsable <code>long</code>.
459      */

460     public static long parseLong(String JavaDoc s) throws NumberFormatException JavaDoc {
461     return parseLong(s, 10);
462     }
463
464     /**
465      * Returns a <code>Long</code> object holding the value
466      * extracted from the specified <code>String</code> when parsed
467      * with the radix given by the second argument. The first
468      * argument is interpreted as representing a signed
469      * <code>long</code> in the radix specified by the second
470      * argument, exactly as if the arguments were given to the {@link
471      * #parseLong(java.lang.String, int)} method. The result is a
472      * <code>Long</code> object that represents the <code>long</code>
473      * value specified by the string.
474      * <p>
475      * In other words, this method returns a <code>Long</code> object equal
476      * to the value of:
477      *
478      * <blockquote><code>
479      * new Long(Long.parseLong(s, radix))
480      * </code></blockquote>
481      *
482      * @param s the string to be parsed
483      * @param radix the radix to be used in interpreting <code>s</code>
484      * @return a <code>Long</code> object holding the value
485      * represented by the string argument in the specified
486      * radix.
487      * @exception NumberFormatException If the <code>String</code> does not
488      * contain a parsable <code>long</code>.
489      */

490     public static Long JavaDoc valueOf(String JavaDoc s, int radix) throws NumberFormatException JavaDoc {
491     return new Long JavaDoc(parseLong(s, radix));
492     }
493
494     /**
495      * Returns a <code>Long</code> object holding the value
496      * of the specified <code>String</code>. The argument is
497      * interpreted as representing a signed decimal <code>long</code>,
498      * exactly as if the argument were given to the {@link
499      * #parseLong(java.lang.String)} method. The result is a
500      * <code>Long</code> object that represents the integer value
501      * specified by the string.
502      * <p>
503      * In other words, this method returns a <code>Long</code> object
504      * equal to the value of:
505      *
506      * <blockquote><pre>
507      * new Long(Long.parseLong(s))
508      * </pre></blockquote>
509      *
510      * @param s the string to be parsed.
511      * @return a <code>Long</code> object holding the value
512      * represented by the string argument.
513      * @exception NumberFormatException If the string cannot be parsed
514      * as a <code>long</code>.
515      */

516     public static Long JavaDoc valueOf(String JavaDoc s) throws NumberFormatException JavaDoc
517     {
518     return new Long JavaDoc(parseLong(s, 10));
519     }
520
521     private static class LongCache {
522     private LongCache(){}
523
524     static final Long JavaDoc cache[] = new Long JavaDoc[-(-128) + 127 + 1];
525
526     static {
527         for(int i = 0; i < cache.length; i++)
528         cache[i] = new Long JavaDoc(i - 128);
529     }
530     }
531
532     /**
533      * Returns a <tt>Long</tt> instance representing the specified
534      * <tt>long</tt> value.
535      * If a new <tt>Long</tt> instance is not required, this method
536      * should generally be used in preference to the constructor
537      * {@link #Long(long)}, as this method is likely to yield
538      * significantly better space and time performance by caching
539      * frequently requested values.
540      *
541      * @param l a long value.
542      * @return a <tt>Long</tt> instance representing <tt>l</tt>.
543      * @since 1.5
544      */

545     public static Long JavaDoc valueOf(long l) {
546     final int offset = 128;
547     if (l >= -128 && l <= 127) { // will cache
548
return LongCache.cache[(int)l + offset];
549     }
550         return new Long JavaDoc(l);
551     }
552
553     /**
554      * Decodes a <code>String</code> into a <code>Long</code>.
555      * Accepts decimal, hexadecimal, and octal numbers given by the
556      * following grammar:
557      *
558      * <blockquote>
559      * <dl>
560      * <dt><i>DecodableString:</i>
561      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
562      * <dd><i>Sign<sub>opt</sub></i> <code>0x</code> <i>HexDigits</i>
563      * <dd><i>Sign<sub>opt</sub></i> <code>0X</code> <i>HexDigits</i>
564      * <dd><i>Sign<sub>opt</sub></i> <code>#</code> <i>HexDigits</i>
565      * <dd><i>Sign<sub>opt</sub></i> <code>0</code> <i>OctalDigits</i>
566      * <p>
567      * <dt><i>Sign:</i>
568      * <dd><code>-</code>
569      * </dl>
570      * </blockquote>
571      *
572      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
573      * are defined in <a HREF="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#48282">&sect;3.10.1</a>
574      * of the <a HREF="http://java.sun.com/docs/books/jls/html/">Java
575      * Language Specification</a>.
576      * <p>
577      * The sequence of characters following an (optional) negative
578      * sign and/or radix specifier (&quot;<code>0x</code>&quot;,
579      * &quot;<code>0X</code>&quot;, &quot;<code>#</code>&quot;, or
580      * leading zero) is parsed as by the <code>Long.parseLong</code>
581      * method with the indicated radix (10, 16, or 8). This sequence
582      * of characters must represent a positive value or a {@link
583      * NumberFormatException} will be thrown. The result is negated
584      * if first character of the specified <code>String</code> is the
585      * minus sign. No whitespace characters are permitted in the
586      * <code>String</code>.
587      *
588      * @param nm the <code>String</code> to decode.
589      * @return a <code>Long</code> object holding the <code>long</code>
590      * value represented by <code>nm</code>
591      * @exception NumberFormatException if the <code>String</code> does not
592      * contain a parsable <code>long</code>.
593      * @see java.lang.Long#parseLong(String, int)
594      * @since 1.2
595      */

596     public static Long JavaDoc decode(String JavaDoc nm) throws NumberFormatException JavaDoc {
597         int radix = 10;
598         int index = 0;
599         boolean negative = false;
600         Long JavaDoc result;
601
602         // Handle minus sign, if present
603
if (nm.startsWith("-")) {
604             negative = true;
605             index++;
606         }
607
608         // Handle radix specifier, if present
609
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
610         index += 2;
611             radix = 16;
612     }
613     else if (nm.startsWith("#", index)) {
614         index ++;
615             radix = 16;
616     }
617     else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
618         index ++;
619             radix = 8;
620     }
621
622         if (nm.startsWith("-", index))
623             throw new NumberFormatException JavaDoc("Negative sign in wrong position");
624
625         try {
626             result = Long.valueOf(nm.substring(index), radix);
627             result = negative ? new Long JavaDoc((long)-result.longValue()) : result;
628         } catch (NumberFormatException JavaDoc e) {
629             // If number is Long.MIN_VALUE, we'll end up here. The next line
630
// handles this case, and causes any genuine format error to be
631
// rethrown.
632
String JavaDoc constant = negative ? new String JavaDoc("-" + nm.substring(index))
633                                        : nm.substring(index);
634             result = Long.valueOf(constant, radix);
635         }
636         return result;
637     }
638
639     /**
640      * The value of the <code>Long</code>.
641      *
642      * @serial
643      */

644     private final long value;
645
646     /**
647      * Constructs a newly allocated <code>Long</code> object that
648      * represents the specified <code>long</code> argument.
649      *
650      * @param value the value to be represented by the
651      * <code>Long</code> object.
652      */

653     public Long(long value) {
654     this.value = value;
655     }
656
657     /**
658      * Constructs a newly allocated <code>Long</code> object that
659      * represents the <code>long</code> value indicated by the
660      * <code>String</code> parameter. The string is converted to a
661      * <code>long</code> value in exactly the manner used by the
662      * <code>parseLong</code> method for radix 10.
663      *
664      * @param s the <code>String</code> to be converted to a
665      * <code>Long</code>.
666      * @exception NumberFormatException if the <code>String</code> does not
667      * contain a parsable <code>long</code>.
668      * @see java.lang.Long#parseLong(java.lang.String, int)
669      */

670     public Long(String JavaDoc s) throws NumberFormatException JavaDoc {
671     this.value = parseLong(s, 10);
672     }
673
674     /**
675      * Returns the value of this <code>Long</code> as a
676      * <code>byte</code>.
677      */

678     public byte byteValue() {
679     return (byte)value;
680     }
681
682     /**
683      * Returns the value of this <code>Long</code> as a
684      * <code>short</code>.
685      */

686     public short shortValue() {
687     return (short)value;
688     }
689
690     /**
691      * Returns the value of this <code>Long</code> as an
692      * <code>int</code>.
693      */

694     public int intValue() {
695     return (int)value;
696     }
697
698     /**
699      * Returns the value of this <code>Long</code> as a
700      * <code>long</code> value.
701      */

702     public long longValue() {
703     return (long)value;
704     }
705
706     /**
707      * Returns the value of this <code>Long</code> as a
708      * <code>float</code>.
709      */

710     public float floatValue() {
711     return (float)value;
712     }
713
714     /**
715      * Returns the value of this <code>Long</code> as a
716      * <code>double</code>.
717      */

718     public double doubleValue() {
719     return (double)value;
720     }
721
722     /**
723      * Returns a <code>String</code> object representing this
724      * <code>Long</code>'s value. The value is converted to signed
725      * decimal representation and returned as a string, exactly as if
726      * the <code>long</code> value were given as an argument to the
727      * {@link java.lang.Long#toString(long)} method.
728      *
729      * @return a string representation of the value of this object in
730      * base&nbsp;10.
731      */

732     public String JavaDoc toString() {
733     return String.valueOf(value);
734     }
735
736     /**
737      * Returns a hash code for this <code>Long</code>. The result is
738      * the exclusive OR of the two halves of the primitive
739      * <code>long</code> value held by this <code>Long</code>
740      * object. That is, the hashcode is the value of the expression:
741      * <blockquote><pre>
742      * (int)(this.longValue()^(this.longValue()&gt;&gt;&gt;32))
743      * </pre></blockquote>
744      *
745      * @return a hash code value for this object.
746      */

747     public int hashCode() {
748     return (int)(value ^ (value >>> 32));
749     }
750
751     /**
752      * Compares this object to the specified object. The result is
753      * <code>true</code> if and only if the argument is not
754      * <code>null</code> and is a <code>Long</code> object that
755      * contains the same <code>long</code> value as this object.
756      *
757      * @param obj the object to compare with.
758      * @return <code>true</code> if the objects are the same;
759      * <code>false</code> otherwise.
760      */

761     public boolean equals(Object JavaDoc obj) {
762     if (obj instanceof Long JavaDoc) {
763         return value == ((Long JavaDoc)obj).longValue();
764     }
765     return false;
766     }
767
768     /**
769      * Determines the <code>long</code> value of the system property
770      * with the specified name.
771      * <p>
772      * The first argument is treated as the name of a system property.
773      * System properties are accessible through the {@link
774      * java.lang.System#getProperty(java.lang.String)} method. The
775      * string value of this property is then interpreted as a
776      * <code>long</code> value and a <code>Long</code> object
777      * representing this value is returned. Details of possible
778      * numeric formats can be found with the definition of
779      * <code>getProperty</code>.
780      * <p>
781      * If there is no property with the specified name, if the
782      * specified name is empty or <code>null</code>, or if the
783      * property does not have the correct numeric format, then
784      * <code>null</code> is returned.
785      * <p>
786      * In other words, this method returns a <code>Long</code> object equal to
787      * the value of:
788      * <blockquote><code>
789      * getLong(nm, null)
790      * </code></blockquote>
791      *
792      * @param nm property name.
793      * @return the <code>Long</code> value of the property.
794      * @see java.lang.System#getProperty(java.lang.String)
795      * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
796      */

797     public static Long JavaDoc getLong(String JavaDoc nm) {
798     return getLong(nm, null);
799     }
800
801     /**
802      * Determines the <code>long</code> value of the system property
803      * with the specified name.
804      * <p>
805      * The first argument is treated as the name of a system property.
806      * System properties are accessible through the {@link
807      * java.lang.System#getProperty(java.lang.String)} method. The
808      * string value of this property is then interpreted as a
809      * <code>long</code> value and a <code>Long</code> object
810      * representing this value is returned. Details of possible
811      * numeric formats can be found with the definition of
812      * <code>getProperty</code>.
813      * <p>
814      * The second argument is the default value. A <code>Long</code> object
815      * that represents the value of the second argument is returned if there
816      * is no property of the specified name, if the property does not have
817      * the correct numeric format, or if the specified name is empty or null.
818      * <p>
819      * In other words, this method returns a <code>Long</code> object equal
820      * to the value of:
821      * <blockquote><code>
822      * getLong(nm, new Long(val))
823      * </code></blockquote>
824      * but in practice it may be implemented in a manner such as:
825      * <blockquote><pre>
826      * Long result = getLong(nm, null);
827      * return (result == null) ? new Long(val) : result;
828      * </pre></blockquote>
829      * to avoid the unnecessary allocation of a <code>Long</code> object when
830      * the default value is not needed.
831      *
832      * @param nm property name.
833      * @param val default value.
834      * @return the <code>Long</code> value of the property.
835      * @see java.lang.System#getProperty(java.lang.String)
836      * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
837      */

838     public static Long JavaDoc getLong(String JavaDoc nm, long val) {
839         Long JavaDoc result = Long.getLong(nm, null);
840         return (result == null) ? new Long JavaDoc(val) : result;
841     }
842
843     /**
844      * Returns the <code>long</code> value of the system property with
845      * the specified name. The first argument is treated as the name
846      * of a system property. System properties are accessible through
847      * the {@link java.lang.System#getProperty(java.lang.String)}
848      * method. The string value of this property is then interpreted
849      * as a <code>long</code> value, as per the
850      * <code>Long.decode</code> method, and a <code>Long</code> object
851      * representing this value is returned.
852      * <p><ul>
853      * <li>If the property value begins with the two ASCII characters
854      * <code>0x</code> or the ASCII character <code>#</code>, not followed by
855      * a minus sign, then the rest of it is parsed as a hexadecimal integer
856      * exactly as for the method {@link #valueOf(java.lang.String, int)}
857      * with radix 16.
858      * <li>If the property value begins with the ASCII character
859      * <code>0</code> followed by another character, it is parsed as
860      * an octal integer exactly as by the method {@link
861      * #valueOf(java.lang.String, int)} with radix 8.
862      * <li>Otherwise the property value is parsed as a decimal
863      * integer exactly as by the method
864      * {@link #valueOf(java.lang.String, int)} with radix 10.
865      * </ul>
866      * <p>
867      * Note that, in every case, neither <code>L</code>
868      * (<code>'&#92;u004C'</code>) nor <code>l</code>
869      * (<code>'&#92;u006C'</code>) is permitted to appear at the end
870      * of the property value as a type indicator, as would be
871      * permitted in Java programming language source code.
872      * <p>
873      * The second argument is the default value. The default value is
874      * returned if there is no property of the specified name, if the
875      * property does not have the correct numeric format, or if the
876      * specified name is empty or <code>null</code>.
877      *
878      * @param nm property name.
879      * @param val default value.
880      * @return the <code>Long</code> value of the property.
881      * @see java.lang.System#getProperty(java.lang.String)
882      * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
883      * @see java.lang.Long#decode
884      */

885     public static Long JavaDoc getLong(String JavaDoc nm, Long JavaDoc val) {
886         String JavaDoc v = null;
887         try {
888             v = System.getProperty(nm);
889         } catch (IllegalArgumentException JavaDoc e) {
890         } catch (NullPointerException JavaDoc e) {
891         }
892     if (v != null) {
893         try {
894         return Long.decode(v);
895         } catch (NumberFormatException JavaDoc e) {
896         }
897     }
898     return val;
899     }
900
901     /**
902      * Compares two <code>Long</code> objects numerically.
903      *
904      * @param anotherLong the <code>Long</code> to be compared.
905      * @return the value <code>0</code> if this <code>Long</code> is
906      * equal to the argument <code>Long</code>; a value less than
907      * <code>0</code> if this <code>Long</code> is numerically less
908      * than the argument <code>Long</code>; and a value greater
909      * than <code>0</code> if this <code>Long</code> is numerically
910      * greater than the argument <code>Long</code> (signed
911      * comparison).
912      * @since 1.2
913      */

914     public int compareTo(Long JavaDoc anotherLong) {
915     long thisVal = this.value;
916     long anotherVal = anotherLong.value;
917     return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
918     }
919
920
921     // Bit Twiddling
922

923     /**
924      * The number of bits used to represent a <tt>long</tt> value in two's
925      * complement binary form.
926      *
927      * @since 1.5
928      */

929     public static final int SIZE = 64;
930  
931     /**
932      * Returns an <tt>long</tt> value with at most a single one-bit, in the
933      * position of the highest-order ("leftmost") one-bit in the specified
934      * <tt>long</tt> value. Returns zero if the specified value has no
935      * one-bits in its two's complement binary representation, that is, if it
936      * is equal to zero.
937      *
938      * @return an <tt>long</tt> value with a single one-bit, in the position
939      * of the highest-order one-bit in the specified value, or zero if
940      * the specified value is itself equal to zero.
941      * @since 1.5
942      */

943     public static long highestOneBit(long i) {
944         // HD, Figure 3-1
945
i |= (i >> 1);
946         i |= (i >> 2);
947         i |= (i >> 4);
948         i |= (i >> 8);
949         i |= (i >> 16);
950         i |= (i >> 32);
951         return i - (i >>> 1);
952     }
953
954     /**
955      * Returns an <tt>long</tt> value with at most a single one-bit, in the
956      * position of the lowest-order ("rightmost") one-bit in the specified
957      * <tt>long</tt> value. Returns zero if the specified value has no
958      * one-bits in its two's complement binary representation, that is, if it
959      * is equal to zero.
960      *
961      * @return an <tt>long</tt> value with a single one-bit, in the position
962      * of the lowest-order one-bit in the specified value, or zero if
963      * the specified value is itself equal to zero.
964      * @since 1.5
965      */

966     public static long lowestOneBit(long i) {
967         // HD, Section 2-1
968
return i & -i;
969     }
970  
971     /**
972      * Returns the number of zero bits preceding the highest-order
973      * ("leftmost") one-bit in the two's complement binary representation
974      * of the specified <tt>long</tt> value. Returns 64 if the
975      * specified value has no one-bits in its two's complement representation,
976      * in other words if it is equal to zero.
977      *
978      * <p>Note that this method is closely related to the logarithm base 2.
979      * For all positive <tt>long</tt> values x:
980      * <ul>
981      * <li>floor(log<sub>2</sub>(x)) = <tt>63 - numberOfLeadingZeros(x)</tt>
982      * <li>ceil(log<sub>2</sub>(x)) = <tt>64 - numberOfLeadingZeros(x - 1)</tt>
983      * </ul>
984      *
985      * @return the number of zero bits preceding the highest-order
986      * ("leftmost") one-bit in the two's complement binary representation
987      * of the specified <tt>long</tt> value, or 64 if the value
988      * is equal to zero.
989      * @since 1.5
990      */

991     public static int numberOfLeadingZeros(long i) {
992         // HD, Figure 5-6
993
if (i == 0)
994             return 64;
995         int n = 1;
996     int x = (int)(i >>> 32);
997         if (x == 0) { n += 32; x = (int)i; }
998         if (x >>> 16 == 0) { n += 16; x <<= 16; }
999         if (x >>> 24 == 0) { n += 8; x <<= 8; }
1000        if (x >>> 28 == 0) { n += 4; x <<= 4; }
1001        if (x >>> 30 == 0) { n += 2; x <<= 2; }
1002        n -= x >>> 31;
1003        return n;
1004    }
1005 
1006    /**
1007     * Returns the number of zero bits following the lowest-order ("rightmost")
1008     * one-bit in the two's complement binary representation of the specified
1009     * <tt>long</tt> value. Returns 64 if the specified value has no
1010     * one-bits in its two's complement representation, in other words if it is
1011     * equal to zero.
1012     *
1013     * @return the number of zero bits following the lowest-order ("rightmost")
1014     * one-bit in the two's complement binary representation of the
1015     * specified <tt>long</tt> value, or 64 if the value is equal
1016     * to zero.
1017     * @since 1.5
1018     */

1019    public static int numberOfTrailingZeros(long i) {
1020        // HD, Figure 5-14
1021
int x, y;
1022    if (i == 0) return 64;
1023    int n = 63;
1024    y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32);
1025    y = x <<16; if (y != 0) { n = n -16; x = y; }
1026    y = x << 8; if (y != 0) { n = n - 8; x = y; }
1027    y = x << 4; if (y != 0) { n = n - 4; x = y; }
1028    y = x << 2; if (y != 0) { n = n - 2; x = y; }
1029    return n - ((x << 1) >>> 31);
1030    }
1031
1032    /**
1033     * Returns the number of one-bits in the two's complement binary
1034     * representation of the specified <tt>long</tt> value. This function is
1035     * sometimes referred to as the <i>population count</i>.
1036     *
1037     * @return the number of one-bits in the two's complement binary
1038     * representation of the specified <tt>long</tt> value.
1039     * @since 1.5
1040     */

1041     public static int bitCount(long i) {
1042        // HD, Figure 5-14
1043
i = i - ((i >>> 1) & 0x5555555555555555L);
1044    i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L);
1045    i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL;
1046    i = i + (i >>> 8);
1047    i = i + (i >>> 16);
1048    i = i + (i >>> 32);
1049    return (int)i & 0x7f;
1050     }
1051 
1052    /**
1053     * Returns the value obtained by rotating the two's complement binary
1054     * representation of the specified <tt>long</tt> value left by the
1055     * specified number of bits. (Bits shifted out of the left hand, or
1056     * high-order, side reenter on the right, or low-order.)
1057     *
1058     * <p>Note that left rotation with a negative distance is equivalent to
1059     * right rotation: <tt>rotateLeft(val, -distance) == rotateRight(val,
1060     * distance)</tt>. Note also that rotation by any multiple of 64 is a
1061     * no-op, so all but the last six bits of the rotation distance can be
1062     * ignored, even if the distance is negative: <tt>rotateLeft(val,
1063     * distance) == rotateLeft(val, distance & 0x3F)</tt>.
1064     *
1065     * @return the value obtained by rotating the two's complement binary
1066     * representation of the specified <tt>long</tt> value left by the
1067     * specified number of bits.
1068     * @since 1.5
1069     */

1070    public static long rotateLeft(long i, int distance) {
1071        return (i << distance) | (i >>> -distance);
1072    }
1073 
1074    /**
1075     * Returns the value obtained by rotating the two's complement binary
1076     * representation of the specified <tt>long</tt> value right by the
1077     * specified number of bits. (Bits shifted out of the right hand, or
1078     * low-order, side reenter on the left, or high-order.)
1079     *
1080     * <p>Note that right rotation with a negative distance is equivalent to
1081     * left rotation: <tt>rotateRight(val, -distance) == rotateLeft(val,
1082     * distance)</tt>. Note also that rotation by any multiple of 64 is a
1083     * no-op, so all but the last six bits of the rotation distance can be
1084     * ignored, even if the distance is negative: <tt>rotateRight(val,
1085     * distance) == rotateRight(val, distance & 0x3F)</tt>.
1086     *
1087     * @return the value obtained by rotating the two's complement binary
1088     * representation of the specified <tt>long</tt> value right by the
1089     * specified number of bits.
1090     * @since 1.5
1091     */

1092    public static long rotateRight(long i, int distance) {
1093        return (i >>> distance) | (i << -distance);
1094    }
1095 
1096    /**
1097     * Returns the value obtained by reversing the order of the bits in the
1098     * two's complement binary representation of the specified <tt>long</tt>
1099     * value.
1100     *
1101     * @return the value obtained by reversing order of the bits in the
1102     * specified <tt>long</tt> value.
1103     * @since 1.5
1104     */

1105    public static long reverse(long i) {
1106        // HD, Figure 7-1
1107
i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L;
1108    i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L;
1109    i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL;
1110    i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
1111    i = (i << 48) | ((i & 0xffff0000L) << 16) |
1112        ((i >>> 16) & 0xffff0000L) | (i >>> 48);
1113    return i;
1114    }
1115 
1116    /**
1117     * Returns the signum function of the specified <tt>long</tt> value. (The
1118     * return value is -1 if the specified value is negative; 0 if the
1119     * specified value is zero; and 1 if the specified value is positive.)
1120     *
1121     * @return the signum function of the specified <tt>long</tt> value.
1122     * @since 1.5
1123     */

1124    public static int signum(long i) {
1125        // HD, Section 2-7
1126
return (int) ((i >> 63) | (-i >>> 63));
1127    }
1128 
1129    /**
1130     * Returns the value obtained by reversing the order of the bytes in the
1131     * two's complement representation of the specified <tt>long</tt> value.
1132     *
1133     * @return the value obtained by reversing the bytes in the specified
1134     * <tt>long</tt> value.
1135     * @since 1.5
1136     */

1137    public static long reverseBytes(long i) {
1138        i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
1139        return (i << 48) | ((i & 0xffff0000L) << 16) |
1140            ((i >>> 16) & 0xffff0000L) | (i >>> 48);
1141    }
1142
1143    /** use serialVersionUID from JDK 1.0.2 for interoperability */
1144    private static final long serialVersionUID = 4290774380558885855L;
1145}
1146
Popular Tags