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)
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
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
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. */
42 * Instances of class <code>Long</code> represent primitive
43 * <code>long</code> values.
45 * Additionally, this class provides various helper functions and variables
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)
56 * @status updated to 1.5
59 @METHODDEFAULT("O<V,V<C,C<IN,THISLOC=IN,C*,GLOBALLOC=V,RETURNLOC=V")
60 public final class Long //extends Number implements Comparable<Long>
63 * Compatible with JDK 1.0.2+.
65 private static final long serialVersionUID = 4290774380558885855L;
68 * The minimum value a <code>long</code> can represent is
69 * -9223372036854775808L (or -2<sup>63</sup>).
71 public static final long MIN_VALUE = 0x8000000000000000L;
74 * The maximum value a <code>long</code> can represent is
75 * 9223372036854775807 (or 2<sup>63</sup> - 1).
77 public static final long MAX_VALUE = 0x7fffffffffffffffL;
80 * The primitive type <code>long</code> is represented by this
81 * <code>Class</code> object.
84 //public static final Class<Long> TYPE = (Class<Long>) VMClassLoader.getPrimitiveClass ('J');
87 * The number of bits needed to represent a <code>long</code>.
90 public static final int SIZE = 64;
92 // This caches some Long values, and is used by boxing
93 // conversions via valueOf(). We cache at least -128..127;
94 // these constants control how much we actually cache.
95 private static final int MIN_CACHE = -128;
96 private static final int MAX_CACHE = 127;
97 private static final Long[] longCache = new Long[MAX_CACHE - MIN_CACHE + 1];
100 for (int i=MIN_CACHE; i <= MAX_CACHE; i++)
101 longCache[i - MIN_CACHE] = new Long(i);
105 * The immutable value of this Long.
107 * @serial the wrapped long
109 @LOC("V") private final long value;
112 * Create a <code>Long</code> object representing the value of the
113 * <code>long</code> argument.
115 * @param value the value to use
117 public Long(long value)
123 * Create a <code>Long</code> object representing the value of the
124 * argument after conversion to a <code>long</code>.
126 * @param s the string to convert
127 * @throws NumberFormatException if the String does not contain a long
128 * @see #valueOf(String)
130 public Long(String s)
132 value = parseLong(s, 10, false);
136 * Return the size of a string large enough to hold the given number
138 * @param num the number we want the string length for (must be positive)
139 * @param radix the radix (base) that will be used for the string
140 * @return a size sufficient for a string of num
142 private static int stringSize(long num, int radix) {
175 * Converts the <code>long</code> to a <code>String</code> using
176 * the specified radix (base). If the radix exceeds
177 * <code>Character.MIN_RADIX</code> or <code>Character.MAX_RADIX</code>, 10
178 * is used instead. If the result is negative, the leading character is
179 * '-' ('\\u002D'). The remaining characters come from
180 * <code>Character.forDigit(digit, radix)</code> ('0'-'9','a'-'z').
182 * @param num the <code>long</code> to convert to <code>String</code>
183 * @param radix the radix (base) to use in the conversion
184 * @return the <code>String</code> representation of the argument
186 /*public static String toString(long num, int radix)
188 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
191 // Is the value negative?
192 boolean isNeg = num < 0;
194 // Is the string a single character?
195 if (!isNeg && num < radix)
196 return new String(digits, (int)num, 1, true);
198 // Compute string size and allocate buffer
199 // account for a leading '-' if the value is negative
207 // When the value is MIN_VALUE, it overflows when made positive
210 i = size = stringSize(MAX_VALUE, radix) + 2;
211 buffer = new char[size];
212 buffer[--i] = digits[(int) (-(num + radix) % radix)];
213 num = -(num / radix);
217 i = size = stringSize(num, radix) + 1;
218 buffer = new char[size];
223 i = size = stringSize(num, radix);
224 buffer = new char[size];
229 buffer[--i] = digits[(int) (num % radix)];
237 // Package constructor avoids an array copy.
238 return new String(buffer, i, size - i, true);
242 * Converts the <code>long</code> to a <code>String</code> assuming it is
243 * unsigned in base 16.
245 * @param l the <code>long</code> to convert to <code>String</code>
246 * @return the <code>String</code> representation of the argument
248 /*public static String toHexString(long l)
250 return toUnsignedString(l, 4);
254 * Converts the <code>long</code> to a <code>String</code> assuming it is
255 * unsigned in base 8.
257 * @param l the <code>long</code> to convert to <code>String</code>
258 * @return the <code>String</code> representation of the argument
260 /*public static String toOctalString(long l)
262 return toUnsignedString(l, 3);
266 * Converts the <code>long</code> to a <code>String</code> assuming it is
267 * unsigned in base 2.
269 * @param l the <code>long</code> to convert to <code>String</code>
270 * @return the <code>String</code> representation of the argument
272 /*public static String toBinaryString(long l)
274 return toUnsignedString(l, 1);
278 * Converts the <code>long</code> to a <code>String</code> and assumes
281 * @param num the <code>long</code> to convert to <code>String</code>
282 * @return the <code>String</code> representation of the argument
283 * @see #toString(long, int)
285 public static String toString(long num)
287 //return toString(num, 10);
288 return String.valueOf(num);
292 * Converts the specified <code>String</code> into an <code>int</code>
293 * using the specified radix (base). The string must not be <code>null</code>
294 * or empty. It may begin with an optional '-', which will negate the answer,
295 * provided that there are also valid digits. Each digit is parsed as if by
296 * <code>Character.digit(d, radix)</code>, and must be in the range
297 * <code>0</code> to <code>radix - 1</code>. Finally, the result must be
298 * within <code>MIN_VALUE</code> to <code>MAX_VALUE</code>, inclusive.
299 * Unlike Double.parseDouble, you may not have a leading '+'; and 'l' or
300 * 'L' as the last character is only valid in radices 22 or greater, where
301 * it is a digit and not a type indicator.
303 * @param str the <code>String</code> to convert
304 * @param radix the radix (base) to use in the conversion
305 * @return the <code>String</code> argument converted to <code>long</code>
306 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
309 public static long parseLong(String str, int radix)
311 return parseLong(str, radix, false);
315 * Converts the specified <code>String</code> into a <code>long</code>.
316 * This function assumes a radix of 10.
318 * @param s the <code>String</code> to convert
319 * @return the <code>int</code> value of <code>s</code>
320 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
322 * @see #parseLong(String, int)
324 public static long parseLong(String s)
326 return parseLong(s, 10, false);
330 * Creates a new <code>Long</code> object using the <code>String</code>
331 * and specified radix (base).
333 * @param s the <code>String</code> to convert
334 * @param radix the radix (base) to convert with
335 * @return the new <code>Long</code>
336 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
338 * @see #parseLong(String, int)
340 public static Long valueOf(String s, int radix)
342 return valueOf(parseLong(s, radix, false));
346 * Creates a new <code>Long</code> object using the <code>String</code>,
347 * assuming a radix of 10.
349 * @param s the <code>String</code> to convert
350 * @return the new <code>Long</code>
351 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
354 * @see #parseLong(String)
356 public static Long valueOf(String s)
358 return valueOf(parseLong(s, 10, false));
362 * Returns a <code>Long</code> object wrapping the value.
364 * @param val the value to wrap
365 * @return the <code>Long</code>
368 public static Long valueOf(long val)
370 if (val < MIN_CACHE || val > MAX_CACHE)
371 return new Long(val);
373 return longCache[((int)val) - MIN_CACHE];
377 * Convert the specified <code>String</code> into a <code>Long</code>.
378 * The <code>String</code> may represent decimal, hexadecimal, or
381 * <p>The extended BNF grammar is as follows:<br>
383 * <em>DecodableString</em>:
384 * ( [ <code>-</code> ] <em>DecimalNumber</em> )
385 * | ( [ <code>-</code> ] ( <code>0x</code> | <code>0X</code>
386 * | <code>#</code> ) <em>HexDigit</em> { <em>HexDigit</em> } )
387 * | ( [ <code>-</code> ] <code>0</code> { <em>OctalDigit</em> } )
388 * <em>DecimalNumber</em>:
389 * <em>DecimalDigit except '0'</em> { <em>DecimalDigit</em> }
390 * <em>DecimalDigit</em>:
391 * <em>Character.digit(d, 10) has value 0 to 9</em>
392 * <em>OctalDigit</em>:
393 * <em>Character.digit(d, 8) has value 0 to 7</em>
394 * <em>DecimalDigit</em>:
395 * <em>Character.digit(d, 16) has value 0 to 15</em>
397 * Finally, the value must be in the range <code>MIN_VALUE</code> to
398 * <code>MAX_VALUE</code>, or an exception is thrown. Note that you cannot
399 * use a trailing 'l' or 'L', unlike in Java source code.
401 * @param str the <code>String</code> to interpret
402 * @return the value of the String as a <code>Long</code>
403 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
405 * @throws NullPointerException if <code>s</code> is null
408 public static Long decode(String str)
410 return valueOf(parseLong(str, 10, true));
414 * Return the value of this <code>Long</code> as a <code>byte</code>.
416 * @return the byte value
418 public byte byteValue()
424 * Return the value of this <code>Long</code> as a <code>short</code>.
426 * @return the short value
428 public short shortValue()
430 return (short) value;
434 * Return the value of this <code>Long</code> as an <code>int</code>.
436 * @return the int value
438 public int intValue()
444 * Return the value of this <code>Long</code>.
446 * @return the long value
448 public long longValue()
454 * Return the value of this <code>Long</code> as a <code>float</code>.
456 * @return the float value
458 public float floatValue()
464 * Return the value of this <code>Long</code> as a <code>double</code>.
466 * @return the double value
468 public double doubleValue()
474 * Converts the <code>Long</code> value to a <code>String</code> and
475 * assumes a radix of 10.
477 * @return the <code>String</code> representation
479 public String toString()
481 //return toString(value, 10);
482 return String.valueOf(value);
486 * Return a hashcode representing this Object. <code>Long</code>'s hash
487 * code is calculated by <code>(int) (value ^ (value >> 32))</code>.
489 * @return this Object's hash code
491 public int hashCode()
493 return (int) (value ^ (value >>> 32));
497 * Returns <code>true</code> if <code>obj</code> is an instance of
498 * <code>Long</code> and represents the same long value.
500 * @param obj the object to compare
501 * @return whether these Objects are semantically equal
503 public boolean equals(Object obj)
505 return obj instanceof Long && value == ((Long) obj).value;
509 * Get the specified system property as a <code>Long</code>. The
510 * <code>decode()</code> method will be used to interpret the value of
513 * @param nm the name of the system property
514 * @return the system property as a <code>Long</code>, or null if the
515 * property is not found or cannot be decoded
516 * @throws SecurityException if accessing the system property is forbidden
517 * @see System#getProperty(String)
518 * @see #decode(String)
520 public static Long getLong(String nm)
522 return getLong(nm, null);
526 * Get the specified system property as a <code>Long</code>, or use a
527 * default <code>long</code> value if the property is not found or is not
528 * decodable. The <code>decode()</code> method will be used to interpret
529 * the value of the property.
531 * @param nm the name of the system property
532 * @param val the default value
533 * @return the value of the system property, or the default
534 * @throws SecurityException if accessing the system property is forbidden
535 * @see System#getProperty(String)
536 * @see #decode(String)
538 public static Long getLong(String nm, long val)
540 Long result = getLong(nm, null);
541 return result == null ? valueOf(val) : result;
545 * Get the specified system property as a <code>Long</code>, or use a
546 * default <code>Long</code> value if the property is not found or is
547 * not decodable. The <code>decode()</code> method will be used to
548 * interpret the value of the property.
550 * @param nm the name of the system property
551 * @param def the default value
552 * @return the value of the system property, or the default
553 * @throws SecurityException if accessing the system property is forbidden
554 * @see System#getProperty(String)
555 * @see #decode(String)
557 public static Long getLong(String nm, Long def)
559 if (nm == null || "".equals(nm))
561 nm = null;//System.getProperty(nm);
568 catch (NumberFormatException e)
575 * Compare two Longs numerically by comparing their <code>long</code>
576 * values. The result is positive if the first is greater, negative if the
577 * second is greater, and 0 if the two are equal.
579 * @param l the Long to compare
580 * @return the comparison
583 public int compareTo(Long l)
585 if (value == l.value)
587 // Returns just -1 or 1 on inequality; doing math might overflow the long.
588 return value > l.value ? 1 : -1;
592 * Return the number of bits set in x.
593 * @param x value to examine
596 public static int bitCount(long x)
598 // Successively collapse alternating bit groups into a sum.
599 x = ((x >> 1) & 0x5555555555555555L) + (x & 0x5555555555555555L);
600 x = ((x >> 2) & 0x3333333333333333L) + (x & 0x3333333333333333L);
601 int v = (int) ((x >>> 32) + x);
602 v = ((v >> 4) & 0x0f0f0f0f) + (v & 0x0f0f0f0f);
603 v = ((v >> 8) & 0x00ff00ff) + (v & 0x00ff00ff);
604 return ((v >> 16) & 0x0000ffff) + (v & 0x0000ffff);
608 * Rotate x to the left by distance bits.
609 * @param x the value to rotate
610 * @param distance the number of bits by which to rotate
613 public static long rotateLeft(long x, int distance)
615 // This trick works because the shift operators implicitly mask
617 return (x << distance) | (x >>> - distance);
621 * Rotate x to the right by distance bits.
622 * @param x the value to rotate
623 * @param distance the number of bits by which to rotate
626 public static long rotateRight(long x, int distance)
628 // This trick works because the shift operators implicitly mask
630 return (x << - distance) | (x >>> distance);
634 * Find the highest set bit in value, and return a new value
635 * with only that bit set.
636 * @param value the value to examine
639 public static long highestOneBit(long value)
641 value |= value >>> 1;
642 value |= value >>> 2;
643 value |= value >>> 4;
644 value |= value >>> 8;
645 value |= value >>> 16;
646 value |= value >>> 32;
647 return value ^ (value >>> 1);
651 * Return the number of leading zeros in value.
652 * @param value the value to examine
655 public static int numberOfLeadingZeros(long value)
657 value |= value >>> 1;
658 value |= value >>> 2;
659 value |= value >>> 4;
660 value |= value >>> 8;
661 value |= value >>> 16;
662 value |= value >>> 32;
663 return bitCount(~value);
667 * Find the lowest set bit in value, and return a new value
668 * with only that bit set.
669 * @param value the value to examine
672 public static long lowestOneBit(long value)
674 // Classic assembly trick.
675 return value & - value;
679 * Find the number of trailing zeros in value.
680 * @param value the value to examine
683 public static int numberOfTrailingZeros(long value)
685 return bitCount((value & -value) - 1);
689 * Return 1 if x is positive, -1 if it is negative, and 0 if it is
691 * @param x the value to examine
694 public static int signum(long x)
696 return (int) ((x >> 63) | (-x >>> 63));
698 // The LHS propagates the sign bit through every bit in the word;
699 // if X < 0, every bit is set to 1, else 0. if X > 0, the RHS
700 // negates x and shifts the resulting 1 in the sign bit to the
701 // LSB, leaving every other bit 0.
703 // Hacker's Delight, Section 2-7
707 * Reverse the bytes in val.
710 /*public static long reverseBytes(long val)
712 int hi = Integer.reverseBytes((int) val);
713 int lo = Integer.reverseBytes((int) (val >>> 32));
714 return (((long) hi) << 32) | lo;
718 * Reverse the bits in val.
721 /*public static long reverse(long val)
723 long hi = Integer.reverse((int) val) & 0xffffffffL;
724 long lo = Integer.reverse((int) (val >>> 32)) & 0xffffffffL;
725 return (hi << 32) | lo;
729 * Helper for converting unsigned numbers to String.
731 * @param num the number
732 * @param exp log2(digit) (ie. 1, 3, or 4 for binary, oct, hex)
734 /*private static String toUnsignedString(long num, int exp)
736 // Compute string length
738 long copy = num >>> exp;
744 // Quick path for single character strings
746 return new String(digits, (int)num, 1, true);
748 // Encode into buffer
749 int mask = (1 << exp) - 1;
750 char[] buffer = new char[size];
754 buffer[--i] = digits[(int) num & mask];
759 // Package constructor avoids an array copy.
760 return new String(buffer, i, size - i, true);
764 * Helper for parsing longs.
766 * @param str the string to parse
767 * @param radix the radix to use, must be 10 if decode is true
768 * @param decode if called from decode
769 * @return the parsed long value
770 * @throws NumberFormatException if there is an error
771 * @throws NullPointerException if decode is true and str is null
772 * @see #parseLong(String, int)
773 * @see #decode(String)
775 private static long parseLong(String str, int radix, boolean decode)
777 if (! decode && str == null)
778 throw new /*NumberFormat*/Exception("NumberFormatException");
780 int len = str.length();
781 boolean isNeg = false;
783 throw new /*NumberFormat*/Exception("NumberFormatException");
784 int ch = str.charAt(index);
788 throw new /*NumberFormat*/Exception("NumberFormatException");
790 ch = str.charAt(++index);
798 if ((str.charAt(index) & ~('x' ^ 'X')) == 'X')
813 throw new /*NumberFormat*/Exception("NumberFormatException");
815 long max = MAX_VALUE / radix;
816 // We can't directly write `max = (MAX_VALUE + 1) / radix'.
817 // So instead we fake it.
818 if (isNeg && MAX_VALUE % radix == radix - 1)
824 if (val < 0 || val > max)
825 throw new /*NumberFormat*/Exception("NumberFormatException");
827 ch = Character.digit(str.charAt(index++), radix);
828 val = val * radix + ch;
829 if (ch < 0 || (val < 0 && (! isNeg || val != MIN_VALUE)))
830 throw new /*NumberFormat*/Exception("NumberFormatException");
832 return isNeg ? -val : val;