libjava/ChangeLog:
[official-gcc.git] / libjava / classpath / java / lang / Long.java
bloba5ee6c707ad2145fd2f692f200de210b1ca1064c
1 /* Long.java -- object wrapper for long
2 Copyright (C) 1998, 1999, 2001, 2002, 2004, 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 * @author Tom Tromey (tromey@redhat.com)
53 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
54 * @author Ian Rogers
55 * @since 1.0
56 * @status updated to 1.5
58 public final class Long extends Number implements Comparable<Long>
60 /**
61 * Compatible with JDK 1.0.2+.
63 private static final long serialVersionUID = 4290774380558885855L;
65 /**
66 * The minimum value a <code>long</code> can represent is
67 * -9223372036854775808L (or -2<sup>63</sup>).
69 public static final long MIN_VALUE = 0x8000000000000000L;
71 /**
72 * The maximum value a <code>long</code> can represent is
73 * 9223372036854775807 (or 2<sup>63</sup> - 1).
75 public static final long MAX_VALUE = 0x7fffffffffffffffL;
77 /**
78 * The primitive type <code>long</code> is represented by this
79 * <code>Class</code> object.
80 * @since 1.1
82 public static final Class<Long> TYPE = (Class<Long>) VMClassLoader.getPrimitiveClass ('J');
84 /**
85 * The number of bits needed to represent a <code>long</code>.
86 * @since 1.5
88 public static final int SIZE = 64;
90 // This caches some Long values, and is used by boxing
91 // conversions via valueOf(). We cache at least -128..127;
92 // these constants control how much we actually cache.
93 private static final int MIN_CACHE = -128;
94 private static final int MAX_CACHE = 127;
95 private static final Long[] longCache = new Long[MAX_CACHE - MIN_CACHE + 1];
96 static
98 for (int i=MIN_CACHE; i <= MAX_CACHE; i++)
99 longCache[i - MIN_CACHE] = new Long(i);
103 * The immutable value of this Long.
105 * @serial the wrapped long
107 private final long value;
110 * Create a <code>Long</code> object representing the value of the
111 * <code>long</code> argument.
113 * @param value the value to use
115 public Long(long value)
117 this.value = value;
121 * Create a <code>Long</code> object representing the value of the
122 * argument after conversion to a <code>long</code>.
124 * @param s the string to convert
125 * @throws NumberFormatException if the String does not contain a long
126 * @see #valueOf(String)
128 public Long(String s)
130 value = parseLong(s, 10, false);
134 * Return the size of a string large enough to hold the given number
136 * @param num the number we want the string length for (must be positive)
137 * @param radix the radix (base) that will be used for the string
138 * @return a size sufficient for a string of num
140 private static int stringSize(long num, int radix) {
141 int exp;
142 if (radix < 4)
144 exp = 1;
146 else if (radix < 8)
148 exp = 2;
150 else if (radix < 16)
152 exp = 3;
154 else if (radix < 32)
156 exp = 4;
158 else
160 exp = 5;
162 int size=0;
165 num >>>= exp;
166 size++;
168 while(num != 0);
169 return size;
173 * Converts the <code>long</code> to a <code>String</code> using
174 * the specified radix (base). If the radix exceeds
175 * <code>Character.MIN_RADIX</code> or <code>Character.MAX_RADIX</code>, 10
176 * is used instead. If the result is negative, the leading character is
177 * '-' ('\\u002D'). The remaining characters come from
178 * <code>Character.forDigit(digit, radix)</code> ('0'-'9','a'-'z').
180 * @param num the <code>long</code> to convert to <code>String</code>
181 * @param radix the radix (base) to use in the conversion
182 * @return the <code>String</code> representation of the argument
184 public static String toString(long num, int radix)
186 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
187 radix = 10;
189 // Is the value negative?
190 boolean isNeg = num < 0;
192 // Is the string a single character?
193 if (!isNeg && num < radix)
194 return new String(digits, (int)num, 1, true);
196 // Compute string size and allocate buffer
197 // account for a leading '-' if the value is negative
198 int size;
199 int i;
200 char[] buffer;
201 if (isNeg)
203 num = -num;
205 // When the value is MIN_VALUE, it overflows when made positive
206 if (num < 0)
208 i = size = stringSize(MAX_VALUE, radix) + 2;
209 buffer = new char[size];
210 buffer[--i] = digits[(int) (-(num + radix) % radix)];
211 num = -(num / radix);
213 else
215 i = size = stringSize(num, radix) + 1;
216 buffer = new char[size];
219 else
221 i = size = stringSize(num, radix);
222 buffer = new char[size];
227 buffer[--i] = digits[(int) (num % radix)];
228 num /= radix;
230 while (num > 0);
232 if (isNeg)
233 buffer[--i] = '-';
235 // Package constructor avoids an array copy.
236 return new String(buffer, i, size - i, true);
240 * Converts the <code>long</code> to a <code>String</code> assuming it is
241 * unsigned in base 16.
243 * @param l the <code>long</code> to convert to <code>String</code>
244 * @return the <code>String</code> representation of the argument
246 public static String toHexString(long l)
248 return toUnsignedString(l, 4);
252 * Converts the <code>long</code> to a <code>String</code> assuming it is
253 * unsigned in base 8.
255 * @param l the <code>long</code> to convert to <code>String</code>
256 * @return the <code>String</code> representation of the argument
258 public static String toOctalString(long l)
260 return toUnsignedString(l, 3);
264 * Converts the <code>long</code> to a <code>String</code> assuming it is
265 * unsigned in base 2.
267 * @param l the <code>long</code> to convert to <code>String</code>
268 * @return the <code>String</code> representation of the argument
270 public static String toBinaryString(long l)
272 return toUnsignedString(l, 1);
276 * Converts the <code>long</code> to a <code>String</code> and assumes
277 * a radix of 10.
279 * @param num the <code>long</code> to convert to <code>String</code>
280 * @return the <code>String</code> representation of the argument
281 * @see #toString(long, int)
283 public static String toString(long num)
285 return toString(num, 10);
289 * Converts the specified <code>String</code> into an <code>int</code>
290 * using the specified radix (base). The string must not be <code>null</code>
291 * or empty. It may begin with an optional '-', which will negate the answer,
292 * provided that there are also valid digits. Each digit is parsed as if by
293 * <code>Character.digit(d, radix)</code>, and must be in the range
294 * <code>0</code> to <code>radix - 1</code>. Finally, the result must be
295 * within <code>MIN_VALUE</code> to <code>MAX_VALUE</code>, inclusive.
296 * Unlike Double.parseDouble, you may not have a leading '+'; and 'l' or
297 * 'L' as the last character is only valid in radices 22 or greater, where
298 * it is a digit and not a type indicator.
300 * @param str the <code>String</code> to convert
301 * @param radix the radix (base) to use in the conversion
302 * @return the <code>String</code> argument converted to <code>long</code>
303 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
304 * <code>long</code>
306 public static long parseLong(String str, int radix)
308 return parseLong(str, radix, false);
312 * Converts the specified <code>String</code> into a <code>long</code>.
313 * This function assumes a radix of 10.
315 * @param s the <code>String</code> to convert
316 * @return the <code>int</code> value of <code>s</code>
317 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
318 * <code>long</code>
319 * @see #parseLong(String, int)
321 public static long parseLong(String s)
323 return parseLong(s, 10, false);
327 * Creates a new <code>Long</code> object using the <code>String</code>
328 * and specified radix (base).
330 * @param s the <code>String</code> to convert
331 * @param radix the radix (base) to convert with
332 * @return the new <code>Long</code>
333 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
334 * <code>long</code>
335 * @see #parseLong(String, int)
337 public static Long valueOf(String s, int radix)
339 return valueOf(parseLong(s, radix, false));
343 * Creates a new <code>Long</code> object using the <code>String</code>,
344 * assuming a radix of 10.
346 * @param s the <code>String</code> to convert
347 * @return the new <code>Long</code>
348 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
349 * <code>long</code>
350 * @see #Long(String)
351 * @see #parseLong(String)
353 public static Long valueOf(String s)
355 return valueOf(parseLong(s, 10, false));
359 * Returns a <code>Long</code> object wrapping the value.
361 * @param val the value to wrap
362 * @return the <code>Long</code>
363 * @since 1.5
365 public static Long valueOf(long val)
367 if (val < MIN_CACHE || val > MAX_CACHE)
368 return new Long(val);
369 else
370 return longCache[((int)val) - MIN_CACHE];
374 * Convert the specified <code>String</code> into a <code>Long</code>.
375 * The <code>String</code> may represent decimal, hexadecimal, or
376 * octal numbers.
378 * <p>The extended BNF grammar is as follows:<br>
379 * <pre>
380 * <em>DecodableString</em>:
381 * ( [ <code>-</code> ] <em>DecimalNumber</em> )
382 * | ( [ <code>-</code> ] ( <code>0x</code> | <code>0X</code>
383 * | <code>#</code> ) <em>HexDigit</em> { <em>HexDigit</em> } )
384 * | ( [ <code>-</code> ] <code>0</code> { <em>OctalDigit</em> } )
385 * <em>DecimalNumber</em>:
386 * <em>DecimalDigit except '0'</em> { <em>DecimalDigit</em> }
387 * <em>DecimalDigit</em>:
388 * <em>Character.digit(d, 10) has value 0 to 9</em>
389 * <em>OctalDigit</em>:
390 * <em>Character.digit(d, 8) has value 0 to 7</em>
391 * <em>DecimalDigit</em>:
392 * <em>Character.digit(d, 16) has value 0 to 15</em>
393 * </pre>
394 * Finally, the value must be in the range <code>MIN_VALUE</code> to
395 * <code>MAX_VALUE</code>, or an exception is thrown. Note that you cannot
396 * use a trailing 'l' or 'L', unlike in Java source code.
398 * @param str the <code>String</code> to interpret
399 * @return the value of the String as a <code>Long</code>
400 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
401 * <code>long</code>
402 * @throws NullPointerException if <code>s</code> is null
403 * @since 1.2
405 public static Long decode(String str)
407 return valueOf(parseLong(str, 10, true));
411 * Return the value of this <code>Long</code> as a <code>byte</code>.
413 * @return the byte value
415 public byte byteValue()
417 return (byte) value;
421 * Return the value of this <code>Long</code> as a <code>short</code>.
423 * @return the short value
425 public short shortValue()
427 return (short) value;
431 * Return the value of this <code>Long</code> as an <code>int</code>.
433 * @return the int value
435 public int intValue()
437 return (int) value;
441 * Return the value of this <code>Long</code>.
443 * @return the long value
445 public long longValue()
447 return value;
451 * Return the value of this <code>Long</code> as a <code>float</code>.
453 * @return the float value
455 public float floatValue()
457 return value;
461 * Return the value of this <code>Long</code> as a <code>double</code>.
463 * @return the double value
465 public double doubleValue()
467 return value;
471 * Converts the <code>Long</code> value to a <code>String</code> and
472 * assumes a radix of 10.
474 * @return the <code>String</code> representation
476 public String toString()
478 return toString(value, 10);
482 * Return a hashcode representing this Object. <code>Long</code>'s hash
483 * code is calculated by <code>(int) (value ^ (value &gt;&gt; 32))</code>.
485 * @return this Object's hash code
487 public int hashCode()
489 return (int) (value ^ (value >>> 32));
493 * Returns <code>true</code> if <code>obj</code> is an instance of
494 * <code>Long</code> and represents the same long value.
496 * @param obj the object to compare
497 * @return whether these Objects are semantically equal
499 public boolean equals(Object obj)
501 return obj instanceof Long && value == ((Long) obj).value;
505 * Get the specified system property as a <code>Long</code>. The
506 * <code>decode()</code> method will be used to interpret the value of
507 * the property.
509 * @param nm the name of the system property
510 * @return the system property as a <code>Long</code>, or null if the
511 * property is not found or cannot be decoded
512 * @throws SecurityException if accessing the system property is forbidden
513 * @see System#getProperty(String)
514 * @see #decode(String)
516 public static Long getLong(String nm)
518 return getLong(nm, null);
522 * Get the specified system property as a <code>Long</code>, or use a
523 * default <code>long</code> value if the property is not found or is not
524 * decodable. The <code>decode()</code> method will be used to interpret
525 * the value of the property.
527 * @param nm the name of the system property
528 * @param val the default value
529 * @return the value of the system property, or the default
530 * @throws SecurityException if accessing the system property is forbidden
531 * @see System#getProperty(String)
532 * @see #decode(String)
534 public static Long getLong(String nm, long val)
536 Long result = getLong(nm, null);
537 return result == null ? valueOf(val) : result;
541 * Get the specified system property as a <code>Long</code>, or use a
542 * default <code>Long</code> value if the property is not found or is
543 * not decodable. The <code>decode()</code> method will be used to
544 * interpret the value of the property.
546 * @param nm the name of the system property
547 * @param def the default value
548 * @return the value of the system property, or the default
549 * @throws SecurityException if accessing the system property is forbidden
550 * @see System#getProperty(String)
551 * @see #decode(String)
553 public static Long getLong(String nm, Long def)
555 if (nm == null || "".equals(nm))
556 return def;
557 nm = System.getProperty(nm);
558 if (nm == null)
559 return def;
562 return decode(nm);
564 catch (NumberFormatException e)
566 return def;
571 * Compare two Longs numerically by comparing their <code>long</code>
572 * values. The result is positive if the first is greater, negative if the
573 * second is greater, and 0 if the two are equal.
575 * @param l the Long to compare
576 * @return the comparison
577 * @since 1.2
579 public int compareTo(Long l)
581 if (value == l.value)
582 return 0;
583 // Returns just -1 or 1 on inequality; doing math might overflow the long.
584 return value > l.value ? 1 : -1;
588 * Return the number of bits set in x.
589 * @param x value to examine
590 * @since 1.5
592 public static int bitCount(long x)
594 // Successively collapse alternating bit groups into a sum.
595 x = ((x >> 1) & 0x5555555555555555L) + (x & 0x5555555555555555L);
596 x = ((x >> 2) & 0x3333333333333333L) + (x & 0x3333333333333333L);
597 int v = (int) ((x >>> 32) + x);
598 v = ((v >> 4) & 0x0f0f0f0f) + (v & 0x0f0f0f0f);
599 v = ((v >> 8) & 0x00ff00ff) + (v & 0x00ff00ff);
600 return ((v >> 16) & 0x0000ffff) + (v & 0x0000ffff);
604 * Rotate x to the left by distance bits.
605 * @param x the value to rotate
606 * @param distance the number of bits by which to rotate
607 * @since 1.5
609 public static long rotateLeft(long x, int distance)
611 // This trick works because the shift operators implicitly mask
612 // the shift count.
613 return (x << distance) | (x >>> - distance);
617 * Rotate x to the right by distance bits.
618 * @param x the value to rotate
619 * @param distance the number of bits by which to rotate
620 * @since 1.5
622 public static long rotateRight(long x, int distance)
624 // This trick works because the shift operators implicitly mask
625 // the shift count.
626 return (x << - distance) | (x >>> distance);
630 * Find the highest set bit in value, and return a new value
631 * with only that bit set.
632 * @param value the value to examine
633 * @since 1.5
635 public static long highestOneBit(long value)
637 value |= value >>> 1;
638 value |= value >>> 2;
639 value |= value >>> 4;
640 value |= value >>> 8;
641 value |= value >>> 16;
642 value |= value >>> 32;
643 return value ^ (value >>> 1);
647 * Return the number of leading zeros in value.
648 * @param value the value to examine
649 * @since 1.5
651 public static int numberOfLeadingZeros(long value)
653 value |= value >>> 1;
654 value |= value >>> 2;
655 value |= value >>> 4;
656 value |= value >>> 8;
657 value |= value >>> 16;
658 value |= value >>> 32;
659 return bitCount(~value);
663 * Find the lowest set bit in value, and return a new value
664 * with only that bit set.
665 * @param value the value to examine
666 * @since 1.5
668 public static long lowestOneBit(long value)
670 // Classic assembly trick.
671 return value & - value;
675 * Find the number of trailing zeros in value.
676 * @param value the value to examine
677 * @since 1.5
679 public static int numberOfTrailingZeros(long value)
681 return bitCount((value & -value) - 1);
685 * Return 1 if x is positive, -1 if it is negative, and 0 if it is
686 * zero.
687 * @param x the value to examine
688 * @since 1.5
690 public static int signum(long x)
692 return (int) ((x >> 63) | (-x >>> 63));
694 // The LHS propagates the sign bit through every bit in the word;
695 // if X < 0, every bit is set to 1, else 0. if X > 0, the RHS
696 // negates x and shifts the resulting 1 in the sign bit to the
697 // LSB, leaving every other bit 0.
699 // Hacker's Delight, Section 2-7
703 * Reverse the bytes in val.
704 * @since 1.5
706 public static long reverseBytes(long val)
708 int hi = Integer.reverseBytes((int) val);
709 int lo = Integer.reverseBytes((int) (val >>> 32));
710 return (((long) hi) << 32) | lo;
714 * Reverse the bits in val.
715 * @since 1.5
717 public static long reverse(long val)
719 long hi = Integer.reverse((int) val) & 0xffffffffL;
720 long lo = Integer.reverse((int) (val >>> 32)) & 0xffffffffL;
721 return (hi << 32) | lo;
725 * Helper for converting unsigned numbers to String.
727 * @param num the number
728 * @param exp log2(digit) (ie. 1, 3, or 4 for binary, oct, hex)
730 private static String toUnsignedString(long num, int exp)
732 // Compute string length
733 int size = 1;
734 long copy = num >>> exp;
735 while (copy != 0)
737 size++;
738 copy >>>= exp;
740 // Quick path for single character strings
741 if (size == 1)
742 return new String(digits, (int)num, 1, true);
744 // Encode into buffer
745 int mask = (1 << exp) - 1;
746 char[] buffer = new char[size];
747 int i = size;
750 buffer[--i] = digits[(int) num & mask];
751 num >>>= exp;
753 while (num != 0);
755 // Package constructor avoids an array copy.
756 return new String(buffer, i, size - i, true);
760 * Helper for parsing longs.
762 * @param str the string to parse
763 * @param radix the radix to use, must be 10 if decode is true
764 * @param decode if called from decode
765 * @return the parsed long value
766 * @throws NumberFormatException if there is an error
767 * @throws NullPointerException if decode is true and str is null
768 * @see #parseLong(String, int)
769 * @see #decode(String)
771 private static long parseLong(String str, int radix, boolean decode)
773 if (! decode && str == null)
774 throw new NumberFormatException();
775 int index = 0;
776 int len = str.length();
777 boolean isNeg = false;
778 if (len == 0)
779 throw new NumberFormatException();
780 int ch = str.charAt(index);
781 if (ch == '-')
783 if (len == 1)
784 throw new NumberFormatException();
785 isNeg = true;
786 ch = str.charAt(++index);
788 if (decode)
790 if (ch == '0')
792 if (++index == len)
793 return 0;
794 if ((str.charAt(index) & ~('x' ^ 'X')) == 'X')
796 radix = 16;
797 index++;
799 else
800 radix = 8;
802 else if (ch == '#')
804 radix = 16;
805 index++;
808 if (index == len)
809 throw new NumberFormatException();
811 long max = MAX_VALUE / radix;
812 // We can't directly write `max = (MAX_VALUE + 1) / radix'.
813 // So instead we fake it.
814 if (isNeg && MAX_VALUE % radix == radix - 1)
815 ++max;
817 long val = 0;
818 while (index < len)
820 if (val < 0 || val > max)
821 throw new NumberFormatException();
823 ch = Character.digit(str.charAt(index++), radix);
824 val = val * radix + ch;
825 if (ch < 0 || (val < 0 && (! isNeg || val != MIN_VALUE)))
826 throw new NumberFormatException();
828 return isNeg ? -val : val;