libjava/
[official-gcc.git] / libjava / classpath / java / lang / Long.java
blob08ac3976ca790319fd588166855a1b9b921876b8
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 * @since 1.0
55 * @status updated to 1.5
57 public final class Long extends Number implements Comparable<Long>
59 /**
60 * Compatible with JDK 1.0.2+.
62 private static final long serialVersionUID = 4290774380558885855L;
64 /**
65 * The minimum value a <code>long</code> can represent is
66 * -9223372036854775808L (or -2<sup>63</sup>).
68 public static final long MIN_VALUE = 0x8000000000000000L;
70 /**
71 * The maximum value a <code>long</code> can represent is
72 * 9223372036854775807 (or 2<sup>63</sup> - 1).
74 public static final long MAX_VALUE = 0x7fffffffffffffffL;
76 /**
77 * The primitive type <code>long</code> is represented by this
78 * <code>Class</code> object.
79 * @since 1.1
81 public static final Class<Long> TYPE = (Class<Long>) VMClassLoader.getPrimitiveClass ('J');
83 /**
84 * The number of bits needed to represent a <code>long</code>.
85 * @since 1.5
87 public static final int SIZE = 64;
89 /**
90 * The immutable value of this Long.
92 * @serial the wrapped long
94 private final long value;
96 /**
97 * Create a <code>Long</code> object representing the value of the
98 * <code>long</code> argument.
100 * @param value the value to use
102 public Long(long value)
104 this.value = value;
108 * Create a <code>Long</code> object representing the value of the
109 * argument after conversion to a <code>long</code>.
111 * @param s the string to convert
112 * @throws NumberFormatException if the String does not contain a long
113 * @see #valueOf(String)
115 public Long(String s)
117 value = parseLong(s, 10, false);
121 * Converts the <code>long</code> to a <code>String</code> using
122 * the specified radix (base). If the radix exceeds
123 * <code>Character.MIN_RADIX</code> or <code>Character.MAX_RADIX</code>, 10
124 * is used instead. If the result is negative, the leading character is
125 * '-' ('\\u002D'). The remaining characters come from
126 * <code>Character.forDigit(digit, radix)</code> ('0'-'9','a'-'z').
128 * @param num the <code>long</code> to convert to <code>String</code>
129 * @param radix the radix (base) to use in the conversion
130 * @return the <code>String</code> representation of the argument
132 public static String toString(long num, int radix)
134 // Use the Integer toString for efficiency if possible.
135 if ((int) num == num)
136 return Integer.toString((int) num, radix);
138 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
139 radix = 10;
141 // For negative numbers, print out the absolute value w/ a leading '-'.
142 // Use an array large enough for a binary number.
143 char[] buffer = new char[65];
144 int i = 65;
145 boolean isNeg = false;
146 if (num < 0)
148 isNeg = true;
149 num = -num;
151 // When the value is MIN_VALUE, it overflows when made positive
152 if (num < 0)
154 buffer[--i] = digits[(int) (-(num + radix) % radix)];
155 num = -(num / radix);
161 buffer[--i] = digits[(int) (num % radix)];
162 num /= radix;
164 while (num > 0);
166 if (isNeg)
167 buffer[--i] = '-';
169 // Package constructor avoids an array copy.
170 return new String(buffer, i, 65 - i, true);
174 * Converts the <code>long</code> to a <code>String</code> assuming it is
175 * unsigned in base 16.
177 * @param l the <code>long</code> to convert to <code>String</code>
178 * @return the <code>String</code> representation of the argument
180 public static String toHexString(long l)
182 return toUnsignedString(l, 4);
186 * Converts the <code>long</code> to a <code>String</code> assuming it is
187 * unsigned in base 8.
189 * @param l the <code>long</code> to convert to <code>String</code>
190 * @return the <code>String</code> representation of the argument
192 public static String toOctalString(long l)
194 return toUnsignedString(l, 3);
198 * Converts the <code>long</code> to a <code>String</code> assuming it is
199 * unsigned in base 2.
201 * @param l the <code>long</code> to convert to <code>String</code>
202 * @return the <code>String</code> representation of the argument
204 public static String toBinaryString(long l)
206 return toUnsignedString(l, 1);
210 * Converts the <code>long</code> to a <code>String</code> and assumes
211 * a radix of 10.
213 * @param num the <code>long</code> to convert to <code>String</code>
214 * @return the <code>String</code> representation of the argument
215 * @see #toString(long, int)
217 public static String toString(long num)
219 return toString(num, 10);
223 * Converts the specified <code>String</code> into an <code>int</code>
224 * using the specified radix (base). The string must not be <code>null</code>
225 * or empty. It may begin with an optional '-', which will negate the answer,
226 * provided that there are also valid digits. Each digit is parsed as if by
227 * <code>Character.digit(d, radix)</code>, and must be in the range
228 * <code>0</code> to <code>radix - 1</code>. Finally, the result must be
229 * within <code>MIN_VALUE</code> to <code>MAX_VALUE</code>, inclusive.
230 * Unlike Double.parseDouble, you may not have a leading '+'; and 'l' or
231 * 'L' as the last character is only valid in radices 22 or greater, where
232 * it is a digit and not a type indicator.
234 * @param str the <code>String</code> to convert
235 * @param radix the radix (base) to use in the conversion
236 * @return the <code>String</code> argument converted to <code>long</code>
237 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
238 * <code>long</code>
240 public static long parseLong(String str, int radix)
242 return parseLong(str, radix, false);
246 * Converts the specified <code>String</code> into a <code>long</code>.
247 * This function assumes a radix of 10.
249 * @param s the <code>String</code> to convert
250 * @return the <code>int</code> value of <code>s</code>
251 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
252 * <code>long</code>
253 * @see #parseLong(String, int)
255 public static long parseLong(String s)
257 return parseLong(s, 10, false);
261 * Creates a new <code>Long</code> object using the <code>String</code>
262 * and specified radix (base).
264 * @param s the <code>String</code> to convert
265 * @param radix the radix (base) to convert with
266 * @return the new <code>Long</code>
267 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
268 * <code>long</code>
269 * @see #parseLong(String, int)
271 public static Long valueOf(String s, int radix)
273 return new Long(parseLong(s, radix, false));
277 * Creates a new <code>Long</code> object using the <code>String</code>,
278 * assuming a radix of 10.
280 * @param s the <code>String</code> to convert
281 * @return the new <code>Long</code>
282 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
283 * <code>long</code>
284 * @see #Long(String)
285 * @see #parseLong(String)
287 public static Long valueOf(String s)
289 return new Long(parseLong(s, 10, false));
293 * Returns a <code>Long</code> object wrapping the value.
295 * @param val the value to wrap
296 * @return the <code>Long</code>
297 * @since 1.5
299 public static Long valueOf(long val)
301 // We aren't required to cache here. We could, though perhaps we
302 // ought to consider that as an empirical question.
303 return new Long(val);
307 * Convert the specified <code>String</code> into a <code>Long</code>.
308 * The <code>String</code> may represent decimal, hexadecimal, or
309 * octal numbers.
311 * <p>The extended BNF grammar is as follows:<br>
312 * <pre>
313 * <em>DecodableString</em>:
314 * ( [ <code>-</code> ] <em>DecimalNumber</em> )
315 * | ( [ <code>-</code> ] ( <code>0x</code> | <code>0X</code>
316 * | <code>#</code> ) <em>HexDigit</em> { <em>HexDigit</em> } )
317 * | ( [ <code>-</code> ] <code>0</code> { <em>OctalDigit</em> } )
318 * <em>DecimalNumber</em>:
319 * <em>DecimalDigit except '0'</em> { <em>DecimalDigit</em> }
320 * <em>DecimalDigit</em>:
321 * <em>Character.digit(d, 10) has value 0 to 9</em>
322 * <em>OctalDigit</em>:
323 * <em>Character.digit(d, 8) has value 0 to 7</em>
324 * <em>DecimalDigit</em>:
325 * <em>Character.digit(d, 16) has value 0 to 15</em>
326 * </pre>
327 * Finally, the value must be in the range <code>MIN_VALUE</code> to
328 * <code>MAX_VALUE</code>, or an exception is thrown. Note that you cannot
329 * use a trailing 'l' or 'L', unlike in Java source code.
331 * @param str the <code>String</code> to interpret
332 * @return the value of the String as a <code>Long</code>
333 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
334 * <code>long</code>
335 * @throws NullPointerException if <code>s</code> is null
336 * @since 1.2
338 public static Long decode(String str)
340 return new Long(parseLong(str, 10, true));
344 * Return the value of this <code>Long</code> as a <code>byte</code>.
346 * @return the byte value
348 public byte byteValue()
350 return (byte) value;
354 * Return the value of this <code>Long</code> as a <code>short</code>.
356 * @return the short value
358 public short shortValue()
360 return (short) value;
364 * Return the value of this <code>Long</code> as an <code>int</code>.
366 * @return the int value
368 public int intValue()
370 return (int) value;
374 * Return the value of this <code>Long</code>.
376 * @return the long value
378 public long longValue()
380 return value;
384 * Return the value of this <code>Long</code> as a <code>float</code>.
386 * @return the float value
388 public float floatValue()
390 return value;
394 * Return the value of this <code>Long</code> as a <code>double</code>.
396 * @return the double value
398 public double doubleValue()
400 return value;
404 * Converts the <code>Long</code> value to a <code>String</code> and
405 * assumes a radix of 10.
407 * @return the <code>String</code> representation
409 public String toString()
411 return toString(value, 10);
415 * Return a hashcode representing this Object. <code>Long</code>'s hash
416 * code is calculated by <code>(int) (value ^ (value &gt;&gt; 32))</code>.
418 * @return this Object's hash code
420 public int hashCode()
422 return (int) (value ^ (value >>> 32));
426 * Returns <code>true</code> if <code>obj</code> is an instance of
427 * <code>Long</code> and represents the same long value.
429 * @param obj the object to compare
430 * @return whether these Objects are semantically equal
432 public boolean equals(Object obj)
434 return obj instanceof Long && value == ((Long) obj).value;
438 * Get the specified system property as a <code>Long</code>. The
439 * <code>decode()</code> method will be used to interpret the value of
440 * the property.
442 * @param nm the name of the system property
443 * @return the system property as a <code>Long</code>, or null if the
444 * property is not found or cannot be decoded
445 * @throws SecurityException if accessing the system property is forbidden
446 * @see System#getProperty(String)
447 * @see #decode(String)
449 public static Long getLong(String nm)
451 return getLong(nm, null);
455 * Get the specified system property as a <code>Long</code>, or use a
456 * default <code>long</code> value if the property is not found or is not
457 * decodable. The <code>decode()</code> method will be used to interpret
458 * the value of the property.
460 * @param nm the name of the system property
461 * @param val the default value
462 * @return the value of the system property, or the default
463 * @throws SecurityException if accessing the system property is forbidden
464 * @see System#getProperty(String)
465 * @see #decode(String)
467 public static Long getLong(String nm, long val)
469 Long result = getLong(nm, null);
470 return result == null ? new Long(val) : result;
474 * Get the specified system property as a <code>Long</code>, or use a
475 * default <code>Long</code> value if the property is not found or is
476 * not decodable. The <code>decode()</code> method will be used to
477 * interpret the value of the property.
479 * @param nm the name of the system property
480 * @param def the default value
481 * @return the value of the system property, or the default
482 * @throws SecurityException if accessing the system property is forbidden
483 * @see System#getProperty(String)
484 * @see #decode(String)
486 public static Long getLong(String nm, Long def)
488 if (nm == null || "".equals(nm))
489 return def;
490 nm = System.getProperty(nm);
491 if (nm == null)
492 return def;
495 return decode(nm);
497 catch (NumberFormatException e)
499 return def;
504 * Compare two Longs numerically by comparing their <code>long</code>
505 * values. The result is positive if the first is greater, negative if the
506 * second is greater, and 0 if the two are equal.
508 * @param l the Long to compare
509 * @return the comparison
510 * @since 1.2
512 public int compareTo(Long l)
514 if (value == l.value)
515 return 0;
516 // Returns just -1 or 1 on inequality; doing math might overflow the long.
517 return value > l.value ? 1 : -1;
521 * Return the number of bits set in x.
522 * @param x value to examine
523 * @since 1.5
525 public static int bitCount(long x)
527 // Successively collapse alternating bit groups into a sum.
528 x = ((x >> 1) & 0x5555555555555555L) + (x & 0x5555555555555555L);
529 x = ((x >> 2) & 0x3333333333333333L) + (x & 0x3333333333333333L);
530 int v = (int) ((x >>> 32) + x);
531 v = ((v >> 4) & 0x0f0f0f0f) + (v & 0x0f0f0f0f);
532 v = ((v >> 8) & 0x00ff00ff) + (v & 0x00ff00ff);
533 return ((v >> 16) & 0x0000ffff) + (v & 0x0000ffff);
537 * Rotate x to the left by distance bits.
538 * @param x the value to rotate
539 * @param distance the number of bits by which to rotate
540 * @since 1.5
542 public static long rotateLeft(long x, int distance)
544 // This trick works because the shift operators implicitly mask
545 // the shift count.
546 return (x << distance) | (x >>> - distance);
550 * Rotate x to the right by distance bits.
551 * @param x the value to rotate
552 * @param distance the number of bits by which to rotate
553 * @since 1.5
555 public static long rotateRight(long x, int distance)
557 // This trick works because the shift operators implicitly mask
558 // the shift count.
559 return (x << - distance) | (x >>> distance);
563 * Find the highest set bit in value, and return a new value
564 * with only that bit set.
565 * @param value the value to examine
566 * @since 1.5
568 public static long highestOneBit(long value)
570 value |= value >>> 1;
571 value |= value >>> 2;
572 value |= value >>> 4;
573 value |= value >>> 8;
574 value |= value >>> 16;
575 value |= value >>> 32;
576 return value ^ (value >>> 1);
580 * Return the number of leading zeros in value.
581 * @param value the value to examine
582 * @since 1.5
584 public static int numberOfLeadingZeros(long value)
586 value |= value >>> 1;
587 value |= value >>> 2;
588 value |= value >>> 4;
589 value |= value >>> 8;
590 value |= value >>> 16;
591 value |= value >>> 32;
592 return bitCount(~value);
596 * Find the lowest set bit in value, and return a new value
597 * with only that bit set.
598 * @param value the value to examine
599 * @since 1.5
601 public static long lowestOneBit(long value)
603 // Classic assembly trick.
604 return value & - value;
608 * Find the number of trailing zeros in value.
609 * @param value the value to examine
610 * @since 1.5
612 public static int numberOfTrailingZeros(long value)
614 return bitCount((value & -value) - 1);
618 * Return 1 if x is positive, -1 if it is negative, and 0 if it is
619 * zero.
620 * @param x the value to examine
621 * @since 1.5
623 public static int signum(long x)
625 return x < 0 ? -1 : (x > 0 ? 1 : 0);
629 * Reverse the bytes in val.
630 * @since 1.5
632 public static long reverseBytes(long val)
634 int hi = Integer.reverseBytes((int) val);
635 int lo = Integer.reverseBytes((int) (val >>> 32));
636 return (((long) hi) << 32) | lo;
640 * Reverse the bits in val.
641 * @since 1.5
643 public static long reverse(long val)
645 long hi = Integer.reverse((int) val) & 0xffffffffL;
646 long lo = Integer.reverse((int) (val >>> 32)) & 0xffffffffL;
647 return (hi << 32) | lo;
651 * Helper for converting unsigned numbers to String.
653 * @param num the number
654 * @param exp log2(digit) (ie. 1, 3, or 4 for binary, oct, hex)
656 private static String toUnsignedString(long num, int exp)
658 // Use the Integer toUnsignedString for efficiency if possible.
659 // If NUM<0 then this particular optimization doesn't work
660 // properly.
661 if (num >= 0 && (int) num == num)
662 return Integer.toUnsignedString((int) num, exp);
664 // Use an array large enough for a binary number.
665 int mask = (1 << exp) - 1;
666 char[] buffer = new char[64];
667 int i = 64;
670 buffer[--i] = digits[(int) num & mask];
671 num >>>= exp;
673 while (num != 0);
675 // Package constructor avoids an array copy.
676 return new String(buffer, i, 64 - i, true);
680 * Helper for parsing longs.
682 * @param str the string to parse
683 * @param radix the radix to use, must be 10 if decode is true
684 * @param decode if called from decode
685 * @return the parsed long value
686 * @throws NumberFormatException if there is an error
687 * @throws NullPointerException if decode is true and str is null
688 * @see #parseLong(String, int)
689 * @see #decode(String)
691 private static long parseLong(String str, int radix, boolean decode)
693 if (! decode && str == null)
694 throw new NumberFormatException();
695 int index = 0;
696 int len = str.length();
697 boolean isNeg = false;
698 if (len == 0)
699 throw new NumberFormatException();
700 int ch = str.charAt(index);
701 if (ch == '-')
703 if (len == 1)
704 throw new NumberFormatException();
705 isNeg = true;
706 ch = str.charAt(++index);
708 if (decode)
710 if (ch == '0')
712 if (++index == len)
713 return 0;
714 if ((str.charAt(index) & ~('x' ^ 'X')) == 'X')
716 radix = 16;
717 index++;
719 else
720 radix = 8;
722 else if (ch == '#')
724 radix = 16;
725 index++;
728 if (index == len)
729 throw new NumberFormatException();
731 long max = MAX_VALUE / radix;
732 // We can't directly write `max = (MAX_VALUE + 1) / radix'.
733 // So instead we fake it.
734 if (isNeg && MAX_VALUE % radix == radix - 1)
735 ++max;
737 long val = 0;
738 while (index < len)
740 if (val < 0 || val > max)
741 throw new NumberFormatException();
743 ch = Character.digit(str.charAt(index++), radix);
744 val = val * radix + ch;
745 if (ch < 0 || (val < 0 && (! isNeg || val != MIN_VALUE)))
746 throw new NumberFormatException();
748 return isNeg ? -val : val;