Dead
[official-gcc.git] / gomp-20050608-branch / libjava / classpath / java / lang / Long.java
blob74e2a52df7cdec74d056e809baf9a52503d247fd
1 /* Long.java -- object wrapper for long
2 Copyright (C) 1998, 1999, 2001, 2002, 2005 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 02110-1301 USA.
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
24 combination.
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
39 package java.lang;
41 /**
42 * Instances of class <code>Long</code> represent primitive
43 * <code>long</code> values.
45 * Additionally, this class provides various helper functions and variables
46 * related to longs.
48 * @author Paul Fisher
49 * @author John Keiser
50 * @author Warren Levy
51 * @author Eric Blake (ebb9@email.byu.edu)
52 * @since 1.0
53 * @status updated to 1.5
55 public final class Long extends Number implements Comparable
57 /**
58 * Compatible with JDK 1.0.2+.
60 private static final long serialVersionUID = 4290774380558885855L;
62 /**
63 * The minimum value a <code>long</code> can represent is
64 * -9223372036854775808L (or -2<sup>63</sup>).
66 public static final long MIN_VALUE = 0x8000000000000000L;
68 /**
69 * The maximum value a <code>long</code> can represent is
70 * 9223372036854775807 (or 2<sup>63</sup> - 1).
72 public static final long MAX_VALUE = 0x7fffffffffffffffL;
74 /**
75 * The primitive type <code>long</code> is represented by this
76 * <code>Class</code> object.
77 * @since 1.1
79 public static final Class TYPE = VMClassLoader.getPrimitiveClass ('J');
81 /**
82 * The number of bits needed to represent a <code>long</code>.
83 * @since 1.5
85 public static final int SIZE = 64;
87 /**
88 * The immutable value of this Long.
90 * @serial the wrapped long
92 private final long value;
94 /**
95 * Create a <code>Long</code> object representing the value of the
96 * <code>long</code> argument.
98 * @param value the value to use
100 public Long(long value)
102 this.value = value;
106 * Create a <code>Long</code> object representing the value of the
107 * argument after conversion to a <code>long</code>.
109 * @param s the string to convert
110 * @throws NumberFormatException if the String does not contain a long
111 * @see #valueOf(String)
113 public Long(String s)
115 value = parseLong(s, 10, false);
119 * Converts the <code>long</code> to a <code>String</code> using
120 * the specified radix (base). If the radix exceeds
121 * <code>Character.MIN_RADIX</code> or <code>Character.MAX_RADIX</code>, 10
122 * is used instead. If the result is negative, the leading character is
123 * '-' ('\\u002D'). The remaining characters come from
124 * <code>Character.forDigit(digit, radix)</code> ('0'-'9','a'-'z').
126 * @param num the <code>long</code> to convert to <code>String</code>
127 * @param radix the radix (base) to use in the conversion
128 * @return the <code>String</code> representation of the argument
130 public static String toString(long num, int radix)
132 // Use the Integer toString for efficiency if possible.
133 if ((int) num == num)
134 return Integer.toString((int) num, radix);
136 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
137 radix = 10;
139 // For negative numbers, print out the absolute value w/ a leading '-'.
140 // Use an array large enough for a binary number.
141 char[] buffer = new char[65];
142 int i = 65;
143 boolean isNeg = false;
144 if (num < 0)
146 isNeg = true;
147 num = -num;
149 // When the value is MIN_VALUE, it overflows when made positive
150 if (num < 0)
152 buffer[--i] = digits[(int) (-(num + radix) % radix)];
153 num = -(num / radix);
159 buffer[--i] = digits[(int) (num % radix)];
160 num /= radix;
162 while (num > 0);
164 if (isNeg)
165 buffer[--i] = '-';
167 // Package constructor avoids an array copy.
168 return new String(buffer, i, 65 - i, true);
172 * Converts the <code>long</code> to a <code>String</code> assuming it is
173 * unsigned in base 16.
175 * @param l the <code>long</code> to convert to <code>String</code>
176 * @return the <code>String</code> representation of the argument
178 public static String toHexString(long l)
180 return toUnsignedString(l, 4);
184 * Converts the <code>long</code> to a <code>String</code> assuming it is
185 * unsigned in base 8.
187 * @param l the <code>long</code> to convert to <code>String</code>
188 * @return the <code>String</code> representation of the argument
190 public static String toOctalString(long l)
192 return toUnsignedString(l, 3);
196 * Converts the <code>long</code> to a <code>String</code> assuming it is
197 * unsigned in base 2.
199 * @param l the <code>long</code> to convert to <code>String</code>
200 * @return the <code>String</code> representation of the argument
202 public static String toBinaryString(long l)
204 return toUnsignedString(l, 1);
208 * Converts the <code>long</code> to a <code>String</code> and assumes
209 * a radix of 10.
211 * @param num the <code>long</code> to convert to <code>String</code>
212 * @return the <code>String</code> representation of the argument
213 * @see #toString(long, int)
215 public static String toString(long num)
217 return toString(num, 10);
221 * Converts the specified <code>String</code> into an <code>int</code>
222 * using the specified radix (base). The string must not be <code>null</code>
223 * or empty. It may begin with an optional '-', which will negate the answer,
224 * provided that there are also valid digits. Each digit is parsed as if by
225 * <code>Character.digit(d, radix)</code>, and must be in the range
226 * <code>0</code> to <code>radix - 1</code>. Finally, the result must be
227 * within <code>MIN_VALUE</code> to <code>MAX_VALUE</code>, inclusive.
228 * Unlike Double.parseDouble, you may not have a leading '+'; and 'l' or
229 * 'L' as the last character is only valid in radices 22 or greater, where
230 * it is a digit and not a type indicator.
232 * @param str the <code>String</code> to convert
233 * @param radix the radix (base) to use in the conversion
234 * @return the <code>String</code> argument converted to <code>long</code>
235 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
236 * <code>long</code>
238 public static long parseLong(String str, int radix)
240 return parseLong(str, radix, false);
244 * Converts the specified <code>String</code> into a <code>long</code>.
245 * This function assumes a radix of 10.
247 * @param s the <code>String</code> to convert
248 * @return the <code>int</code> value of <code>s</code>
249 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
250 * <code>long</code>
251 * @see #parseLong(String, int)
253 public static long parseLong(String s)
255 return parseLong(s, 10, false);
259 * Creates a new <code>Long</code> object using the <code>String</code>
260 * and specified radix (base).
262 * @param s the <code>String</code> to convert
263 * @param radix the radix (base) to convert with
264 * @return the new <code>Long</code>
265 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
266 * <code>long</code>
267 * @see #parseLong(String, int)
269 public static Long valueOf(String s, int radix)
271 return new Long(parseLong(s, radix, false));
275 * Creates a new <code>Long</code> object using the <code>String</code>,
276 * assuming a radix of 10.
278 * @param s the <code>String</code> to convert
279 * @return the new <code>Long</code>
280 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
281 * <code>long</code>
282 * @see #Long(String)
283 * @see #parseLong(String)
285 public static Long valueOf(String s)
287 return new Long(parseLong(s, 10, false));
291 * Returns a <code>Long</code> object wrapping the value.
293 * @param val the value to wrap
294 * @return the <code>Long</code>
296 * @since 1.5
298 public static synchronized Long valueOf(long val)
300 // We aren't required to cache here. We could, though perhaps we
301 // ought to consider that as an empirical question.
302 return new Long(val);
306 * Convert the specified <code>String</code> into a <code>Long</code>.
307 * The <code>String</code> may represent decimal, hexadecimal, or
308 * octal numbers.
310 * <p>The extended BNF grammar is as follows:<br>
311 * <pre>
312 * <em>DecodableString</em>:
313 * ( [ <code>-</code> ] <em>DecimalNumber</em> )
314 * | ( [ <code>-</code> ] ( <code>0x</code> | <code>0X</code>
315 * | <code>#</code> ) <em>HexDigit</em> { <em>HexDigit</em> } )
316 * | ( [ <code>-</code> ] <code>0</code> { <em>OctalDigit</em> } )
317 * <em>DecimalNumber</em>:
318 * <em>DecimalDigit except '0'</em> { <em>DecimalDigit</em> }
319 * <em>DecimalDigit</em>:
320 * <em>Character.digit(d, 10) has value 0 to 9</em>
321 * <em>OctalDigit</em>:
322 * <em>Character.digit(d, 8) has value 0 to 7</em>
323 * <em>DecimalDigit</em>:
324 * <em>Character.digit(d, 16) has value 0 to 15</em>
325 * </pre>
326 * Finally, the value must be in the range <code>MIN_VALUE</code> to
327 * <code>MAX_VALUE</code>, or an exception is thrown. Note that you cannot
328 * use a trailing 'l' or 'L', unlike in Java source code.
330 * @param str the <code>String</code> to interpret
331 * @return the value of the String as a <code>Long</code>
332 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
333 * <code>long</code>
334 * @throws NullPointerException if <code>s</code> is null
335 * @since 1.2
337 public static Long decode(String str)
339 return new Long(parseLong(str, 10, true));
343 * Return the value of this <code>Long</code> as a <code>byte</code>.
345 * @return the byte value
347 public byte byteValue()
349 return (byte) value;
353 * Return the value of this <code>Long</code> as a <code>short</code>.
355 * @return the short value
357 public short shortValue()
359 return (short) value;
363 * Return the value of this <code>Long</code> as an <code>int</code>.
365 * @return the int value
367 public int intValue()
369 return (int) value;
373 * Return the value of this <code>Long</code>.
375 * @return the long value
377 public long longValue()
379 return value;
383 * Return the value of this <code>Long</code> as a <code>float</code>.
385 * @return the float value
387 public float floatValue()
389 return value;
393 * Return the value of this <code>Long</code> as a <code>double</code>.
395 * @return the double value
397 public double doubleValue()
399 return value;
403 * Converts the <code>Long</code> value to a <code>String</code> and
404 * assumes a radix of 10.
406 * @return the <code>String</code> representation
408 public String toString()
410 return toString(value, 10);
414 * Return a hashcode representing this Object. <code>Long</code>'s hash
415 * code is calculated by <code>(int) (value ^ (value &gt;&gt; 32))</code>.
417 * @return this Object's hash code
419 public int hashCode()
421 return (int) (value ^ (value >>> 32));
425 * Returns <code>true</code> if <code>obj</code> is an instance of
426 * <code>Long</code> and represents the same long value.
428 * @param obj the object to compare
429 * @return whether these Objects are semantically equal
431 public boolean equals(Object obj)
433 return obj instanceof Long && value == ((Long) obj).value;
437 * Get the specified system property as a <code>Long</code>. The
438 * <code>decode()</code> method will be used to interpret the value of
439 * the property.
441 * @param nm the name of the system property
442 * @return the system property as a <code>Long</code>, or null if the
443 * property is not found or cannot be decoded
444 * @throws SecurityException if accessing the system property is forbidden
445 * @see System#getProperty(String)
446 * @see #decode(String)
448 public static Long getLong(String nm)
450 return getLong(nm, null);
454 * Get the specified system property as a <code>Long</code>, or use a
455 * default <code>long</code> value if the property is not found or is not
456 * decodable. The <code>decode()</code> method will be used to interpret
457 * the value of the property.
459 * @param nm the name of the system property
460 * @param val the default value
461 * @return the value of the system property, or the default
462 * @throws SecurityException if accessing the system property is forbidden
463 * @see System#getProperty(String)
464 * @see #decode(String)
466 public static Long getLong(String nm, long val)
468 Long result = getLong(nm, null);
469 return result == null ? new Long(val) : result;
473 * Get the specified system property as a <code>Long</code>, or use a
474 * default <code>Long</code> value if the property is not found or is
475 * not decodable. The <code>decode()</code> method will be used to
476 * interpret the value of the property.
478 * @param nm the name of the system property
479 * @param def the default value
480 * @return the value of the system property, or the default
481 * @throws SecurityException if accessing the system property is forbidden
482 * @see System#getProperty(String)
483 * @see #decode(String)
485 public static Long getLong(String nm, Long def)
487 if (nm == null || "".equals(nm))
488 return def;
489 nm = System.getProperty(nm);
490 if (nm == null)
491 return def;
494 return decode(nm);
496 catch (NumberFormatException e)
498 return def;
503 * Compare two Longs numerically by comparing their <code>long</code>
504 * values. The result is positive if the first is greater, negative if the
505 * second is greater, and 0 if the two are equal.
507 * @param l the Long to compare
508 * @return the comparison
509 * @since 1.2
511 public int compareTo(Long l)
513 if (value == l.value)
514 return 0;
515 // Returns just -1 or 1 on inequality; doing math might overflow the long.
516 return value > l.value ? 1 : -1;
520 * Behaves like <code>compareTo(Long)</code> unless the Object
521 * is not a <code>Long</code>.
523 * @param o the object to compare
524 * @return the comparison
525 * @throws ClassCastException if the argument is not a <code>Long</code>
526 * @see #compareTo(Long)
527 * @see Comparable
528 * @since 1.2
530 public int compareTo(Object o)
532 return compareTo((Long) o);
536 * Return the number of bits set in x.
537 * @param x value to examine
538 * @since 1.5
540 public static int bitCount(long x)
542 // Successively collapse alternating bit groups into a sum.
543 x = ((x >> 1) & 0x5555555555555555L) + (x & 0x5555555555555555L);
544 x = ((x >> 2) & 0x3333333333333333L) + (x & 0x3333333333333333L);
545 int v = (int) ((x >>> 32) + x);
546 v = ((v >> 4) & 0x0f0f0f0f) + (v & 0x0f0f0f0f);
547 v = ((v >> 8) & 0x00ff00ff) + (v & 0x00ff00ff);
548 return ((v >> 16) & 0x0000ffff) + (v & 0x0000ffff);
552 * Rotate x to the left by distance bits.
553 * @param x the value to rotate
554 * @param distance the number of bits by which to rotate
555 * @since 1.5
557 public static long rotateLeft(long x, int distance)
559 // This trick works because the shift operators implicitly mask
560 // the shift count.
561 return (x << distance) | (x >>> - distance);
565 * Rotate x to the right by distance bits.
566 * @param x the value to rotate
567 * @param distance the number of bits by which to rotate
568 * @since 1.5
570 public static long rotateRight(long x, int distance)
572 // This trick works because the shift operators implicitly mask
573 // the shift count.
574 return (x << - distance) | (x >>> distance);
578 * Find the highest set bit in value, and return a new value
579 * with only that bit set.
580 * @param value the value to examine
581 * @since 1.5
583 public static long highestOneBit(long value)
585 value |= value >>> 1;
586 value |= value >>> 2;
587 value |= value >>> 4;
588 value |= value >>> 8;
589 value |= value >>> 16;
590 value |= value >>> 32;
591 return value ^ (value >>> 1);
595 * Return the number of leading zeros in value.
596 * @param value the value to examine
597 * @since 1.5
599 public static int numberOfLeadingZeros(long value)
601 value |= value >>> 1;
602 value |= value >>> 2;
603 value |= value >>> 4;
604 value |= value >>> 8;
605 value |= value >>> 16;
606 value |= value >>> 32;
607 return bitCount(~value);
611 * Find the lowest set bit in value, and return a new value
612 * with only that bit set.
613 * @param value the value to examine
614 * @since 1.5
616 public static long lowestOneBit(long value)
618 // Classic assembly trick.
619 return value & - value;
623 * Find the number of trailing zeros in value.
624 * @param value the value to examine
625 * @since 1.5
627 public static int numberOfTrailingZeros(long value)
629 return bitCount((value & -value) - 1);
633 * Return 1 if x is positive, -1 if it is negative, and 0 if it is
634 * zero.
635 * @param x the value to examine
636 * @since 1.5
638 public static int signum(long x)
640 return x < 0 ? -1 : (x > 0 ? 1 : 0);
644 * Reverse the bytes in val.
645 * @since 1.5
647 public static long reverseBytes(long val)
649 int hi = Integer.reverseBytes((int) val);
650 int lo = Integer.reverseBytes((int) (val >>> 32));
651 return (((long) hi) << 32) | lo;
655 * Reverse the bits in val.
656 * @since 1.5
658 public static long reverse(long val)
660 long hi = Integer.reverse((int) val) & 0xffffffffL;
661 long lo = Integer.reverse((int) (val >>> 32)) & 0xffffffffL;
662 return (hi << 32) | lo;
666 * Helper for converting unsigned numbers to String.
668 * @param num the number
669 * @param exp log2(digit) (ie. 1, 3, or 4 for binary, oct, hex)
671 private static String toUnsignedString(long num, int exp)
673 // Use the Integer toUnsignedString for efficiency if possible.
674 // If NUM<0 then this particular optimization doesn't work
675 // properly.
676 if (num >= 0 && (int) num == num)
677 return Integer.toUnsignedString((int) num, exp);
679 // Use an array large enough for a binary number.
680 int mask = (1 << exp) - 1;
681 char[] buffer = new char[64];
682 int i = 64;
685 buffer[--i] = digits[(int) num & mask];
686 num >>>= exp;
688 while (num != 0);
690 // Package constructor avoids an array copy.
691 return new String(buffer, i, 64 - i, true);
695 * Helper for parsing longs.
697 * @param str the string to parse
698 * @param radix the radix to use, must be 10 if decode is true
699 * @param decode if called from decode
700 * @return the parsed long value
701 * @throws NumberFormatException if there is an error
702 * @throws NullPointerException if decode is true and str is null
703 * @see #parseLong(String, int)
704 * @see #decode(String)
706 private static long parseLong(String str, int radix, boolean decode)
708 if (! decode && str == null)
709 throw new NumberFormatException();
710 int index = 0;
711 int len = str.length();
712 boolean isNeg = false;
713 if (len == 0)
714 throw new NumberFormatException();
715 int ch = str.charAt(index);
716 if (ch == '-')
718 if (len == 1)
719 throw new NumberFormatException();
720 isNeg = true;
721 ch = str.charAt(++index);
723 if (decode)
725 if (ch == '0')
727 if (++index == len)
728 return 0;
729 if ((str.charAt(index) & ~('x' ^ 'X')) == 'X')
731 radix = 16;
732 index++;
734 else
735 radix = 8;
737 else if (ch == '#')
739 radix = 16;
740 index++;
743 if (index == len)
744 throw new NumberFormatException();
746 long max = MAX_VALUE / radix;
747 // We can't directly write `max = (MAX_VALUE + 1) / radix'.
748 // So instead we fake it.
749 if (isNeg && MAX_VALUE % radix == radix - 1)
750 ++max;
752 long val = 0;
753 while (index < len)
755 if (val < 0 || val > max)
756 throw new NumberFormatException();
758 ch = Character.digit(str.charAt(index++), radix);
759 val = val * radix + ch;
760 if (ch < 0 || (val < 0 && (! isNeg || val != MIN_VALUE)))
761 throw new NumberFormatException();
763 return isNeg ? -val : val;