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
58 public final class Long //extends Number implements Comparable<Long>
61 * Compatible with JDK 1.0.2+.
63 private static final long serialVersionUID = 4290774380558885855L;
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;
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;
78 * The primitive type <code>long</code> is represented by this
79 * <code>Class</code> object.
82 //public static final Class<Long> TYPE = (Class<Long>) VMClassLoader.getPrimitiveClass ('J');
85 * The number of bits needed to represent a <code>long</code>.
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];
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)
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) {
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)
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
205 // When the value is MIN_VALUE, it overflows when made positive
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);
215 i = size = stringSize(num, radix) + 1;
216 buffer = new char[size];
221 i = size = stringSize(num, radix);
222 buffer = new char[size];
227 buffer[--i] = digits[(int) (num % radix)];
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
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);
286 return String.valueOf(num);
290 * Converts the specified <code>String</code> into an <code>int</code>
291 * using the specified radix (base). The string must not be <code>null</code>
292 * or empty. It may begin with an optional '-', which will negate the answer,
293 * provided that there are also valid digits. Each digit is parsed as if by
294 * <code>Character.digit(d, radix)</code>, and must be in the range
295 * <code>0</code> to <code>radix - 1</code>. Finally, the result must be
296 * within <code>MIN_VALUE</code> to <code>MAX_VALUE</code>, inclusive.
297 * Unlike Double.parseDouble, you may not have a leading '+'; and 'l' or
298 * 'L' as the last character is only valid in radices 22 or greater, where
299 * it is a digit and not a type indicator.
301 * @param str the <code>String</code> to convert
302 * @param radix the radix (base) to use in the conversion
303 * @return the <code>String</code> argument converted to <code>long</code>
304 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
307 public static long parseLong(String str, int radix)
309 return parseLong(str, radix, false);
313 * Converts the specified <code>String</code> into a <code>long</code>.
314 * This function assumes a radix of 10.
316 * @param s the <code>String</code> to convert
317 * @return the <code>int</code> value of <code>s</code>
318 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
320 * @see #parseLong(String, int)
322 public static long parseLong(String s)
324 return parseLong(s, 10, false);
328 * Creates a new <code>Long</code> object using the <code>String</code>
329 * and specified radix (base).
331 * @param s the <code>String</code> to convert
332 * @param radix the radix (base) to convert with
333 * @return the new <code>Long</code>
334 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
336 * @see #parseLong(String, int)
338 public static Long valueOf(String s, int radix)
340 return valueOf(parseLong(s, radix, false));
344 * Creates a new <code>Long</code> object using the <code>String</code>,
345 * assuming a radix of 10.
347 * @param s the <code>String</code> to convert
348 * @return the new <code>Long</code>
349 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
352 * @see #parseLong(String)
354 public static Long valueOf(String s)
356 return valueOf(parseLong(s, 10, false));
360 * Returns a <code>Long</code> object wrapping the value.
362 * @param val the value to wrap
363 * @return the <code>Long</code>
366 public static Long valueOf(long val)
368 if (val < MIN_CACHE || val > MAX_CACHE)
369 return new Long(val);
371 return longCache[((int)val) - MIN_CACHE];
375 * Convert the specified <code>String</code> into a <code>Long</code>.
376 * The <code>String</code> may represent decimal, hexadecimal, or
379 * <p>The extended BNF grammar is as follows:<br>
381 * <em>DecodableString</em>:
382 * ( [ <code>-</code> ] <em>DecimalNumber</em> )
383 * | ( [ <code>-</code> ] ( <code>0x</code> | <code>0X</code>
384 * | <code>#</code> ) <em>HexDigit</em> { <em>HexDigit</em> } )
385 * | ( [ <code>-</code> ] <code>0</code> { <em>OctalDigit</em> } )
386 * <em>DecimalNumber</em>:
387 * <em>DecimalDigit except '0'</em> { <em>DecimalDigit</em> }
388 * <em>DecimalDigit</em>:
389 * <em>Character.digit(d, 10) has value 0 to 9</em>
390 * <em>OctalDigit</em>:
391 * <em>Character.digit(d, 8) has value 0 to 7</em>
392 * <em>DecimalDigit</em>:
393 * <em>Character.digit(d, 16) has value 0 to 15</em>
395 * Finally, the value must be in the range <code>MIN_VALUE</code> to
396 * <code>MAX_VALUE</code>, or an exception is thrown. Note that you cannot
397 * use a trailing 'l' or 'L', unlike in Java source code.
399 * @param str the <code>String</code> to interpret
400 * @return the value of the String as a <code>Long</code>
401 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
403 * @throws NullPointerException if <code>s</code> is null
406 public static Long decode(String str)
408 return valueOf(parseLong(str, 10, true));
412 * Return the value of this <code>Long</code> as a <code>byte</code>.
414 * @return the byte value
416 public byte byteValue()
422 * Return the value of this <code>Long</code> as a <code>short</code>.
424 * @return the short value
426 public short shortValue()
428 return (short) value;
432 * Return the value of this <code>Long</code> as an <code>int</code>.
434 * @return the int value
436 public int intValue()
442 * Return the value of this <code>Long</code>.
444 * @return the long value
446 public long longValue()
452 * Return the value of this <code>Long</code> as a <code>float</code>.
454 * @return the float value
456 public float floatValue()
462 * Return the value of this <code>Long</code> as a <code>double</code>.
464 * @return the double value
466 public double doubleValue()
472 * Converts the <code>Long</code> value to a <code>String</code> and
473 * assumes a radix of 10.
475 * @return the <code>String</code> representation
477 public String toString()
479 //return toString(value, 10);
480 return String.valueOf(value);
484 * Return a hashcode representing this Object. <code>Long</code>'s hash
485 * code is calculated by <code>(int) (value ^ (value >> 32))</code>.
487 * @return this Object's hash code
489 public int hashCode()
491 return (int) (value ^ (value >>> 32));
495 * Returns <code>true</code> if <code>obj</code> is an instance of
496 * <code>Long</code> and represents the same long value.
498 * @param obj the object to compare
499 * @return whether these Objects are semantically equal
501 public boolean equals(Object obj)
503 return obj instanceof Long && value == ((Long) obj).value;
507 * Get the specified system property as a <code>Long</code>. The
508 * <code>decode()</code> method will be used to interpret the value of
511 * @param nm the name of the system property
512 * @return the system property as a <code>Long</code>, or null if the
513 * property is not found or cannot be decoded
514 * @throws SecurityException if accessing the system property is forbidden
515 * @see System#getProperty(String)
516 * @see #decode(String)
518 public static Long getLong(String nm)
520 return getLong(nm, null);
524 * Get the specified system property as a <code>Long</code>, or use a
525 * default <code>long</code> value if the property is not found or is not
526 * decodable. The <code>decode()</code> method will be used to interpret
527 * the value of the property.
529 * @param nm the name of the system property
530 * @param val the default value
531 * @return the value of the system property, or the default
532 * @throws SecurityException if accessing the system property is forbidden
533 * @see System#getProperty(String)
534 * @see #decode(String)
536 public static Long getLong(String nm, long val)
538 Long result = getLong(nm, null);
539 return result == null ? valueOf(val) : result;
543 * Get the specified system property as a <code>Long</code>, or use a
544 * default <code>Long</code> value if the property is not found or is
545 * not decodable. The <code>decode()</code> method will be used to
546 * interpret the value of the property.
548 * @param nm the name of the system property
549 * @param def the default value
550 * @return the value of the system property, or the default
551 * @throws SecurityException if accessing the system property is forbidden
552 * @see System#getProperty(String)
553 * @see #decode(String)
555 public static Long getLong(String nm, Long def)
557 if (nm == null || "".equals(nm))
559 nm = null;//System.getProperty(nm);
566 catch (NumberFormatException e)
573 * Compare two Longs numerically by comparing their <code>long</code>
574 * values. The result is positive if the first is greater, negative if the
575 * second is greater, and 0 if the two are equal.
577 * @param l the Long to compare
578 * @return the comparison
581 public int compareTo(Long l)
583 if (value == l.value)
585 // Returns just -1 or 1 on inequality; doing math might overflow the long.
586 return value > l.value ? 1 : -1;
590 * Return the number of bits set in x.
591 * @param x value to examine
594 public static int bitCount(long x)
596 // Successively collapse alternating bit groups into a sum.
597 x = ((x >> 1) & 0x5555555555555555L) + (x & 0x5555555555555555L);
598 x = ((x >> 2) & 0x3333333333333333L) + (x & 0x3333333333333333L);
599 int v = (int) ((x >>> 32) + x);
600 v = ((v >> 4) & 0x0f0f0f0f) + (v & 0x0f0f0f0f);
601 v = ((v >> 8) & 0x00ff00ff) + (v & 0x00ff00ff);
602 return ((v >> 16) & 0x0000ffff) + (v & 0x0000ffff);
606 * Rotate x to the left by distance bits.
607 * @param x the value to rotate
608 * @param distance the number of bits by which to rotate
611 public static long rotateLeft(long x, int distance)
613 // This trick works because the shift operators implicitly mask
615 return (x << distance) | (x >>> - distance);
619 * Rotate x to the right by distance bits.
620 * @param x the value to rotate
621 * @param distance the number of bits by which to rotate
624 public static long rotateRight(long x, int distance)
626 // This trick works because the shift operators implicitly mask
628 return (x << - distance) | (x >>> distance);
632 * Find the highest set bit in value, and return a new value
633 * with only that bit set.
634 * @param value the value to examine
637 public static long highestOneBit(long value)
639 value |= value >>> 1;
640 value |= value >>> 2;
641 value |= value >>> 4;
642 value |= value >>> 8;
643 value |= value >>> 16;
644 value |= value >>> 32;
645 return value ^ (value >>> 1);
649 * Return the number of leading zeros in value.
650 * @param value the value to examine
653 public static int numberOfLeadingZeros(long value)
655 value |= value >>> 1;
656 value |= value >>> 2;
657 value |= value >>> 4;
658 value |= value >>> 8;
659 value |= value >>> 16;
660 value |= value >>> 32;
661 return bitCount(~value);
665 * Find the lowest set bit in value, and return a new value
666 * with only that bit set.
667 * @param value the value to examine
670 public static long lowestOneBit(long value)
672 // Classic assembly trick.
673 return value & - value;
677 * Find the number of trailing zeros in value.
678 * @param value the value to examine
681 public static int numberOfTrailingZeros(long value)
683 return bitCount((value & -value) - 1);
687 * Return 1 if x is positive, -1 if it is negative, and 0 if it is
689 * @param x the value to examine
692 public static int signum(long x)
694 return (int) ((x >> 63) | (-x >>> 63));
696 // The LHS propagates the sign bit through every bit in the word;
697 // if X < 0, every bit is set to 1, else 0. if X > 0, the RHS
698 // negates x and shifts the resulting 1 in the sign bit to the
699 // LSB, leaving every other bit 0.
701 // Hacker's Delight, Section 2-7
705 * Reverse the bytes in val.
708 /*public static long reverseBytes(long val)
710 int hi = Integer.reverseBytes((int) val);
711 int lo = Integer.reverseBytes((int) (val >>> 32));
712 return (((long) hi) << 32) | lo;
716 * Reverse the bits in val.
719 /*public static long reverse(long val)
721 long hi = Integer.reverse((int) val) & 0xffffffffL;
722 long lo = Integer.reverse((int) (val >>> 32)) & 0xffffffffL;
723 return (hi << 32) | lo;
727 * Helper for converting unsigned numbers to String.
729 * @param num the number
730 * @param exp log2(digit) (ie. 1, 3, or 4 for binary, oct, hex)
732 /*private static String toUnsignedString(long num, int exp)
734 // Compute string length
736 long copy = num >>> exp;
742 // Quick path for single character strings
744 return new String(digits, (int)num, 1, true);
746 // Encode into buffer
747 int mask = (1 << exp) - 1;
748 char[] buffer = new char[size];
752 buffer[--i] = digits[(int) num & mask];
757 // Package constructor avoids an array copy.
758 return new String(buffer, i, size - i, true);
762 * Helper for parsing longs.
764 * @param str the string to parse
765 * @param radix the radix to use, must be 10 if decode is true
766 * @param decode if called from decode
767 * @return the parsed long value
768 * @throws NumberFormatException if there is an error
769 * @throws NullPointerException if decode is true and str is null
770 * @see #parseLong(String, int)
771 * @see #decode(String)
773 private static long parseLong(String str, int radix, boolean decode)
775 if (! decode && str == null)
776 throw new /*NumberFormat*/Exception("NumberFormatException");
778 int len = str.length();
779 boolean isNeg = false;
781 throw new /*NumberFormat*/Exception("NumberFormatException");
782 int ch = str.charAt(index);
786 throw new /*NumberFormat*/Exception("NumberFormatException");
788 ch = str.charAt(++index);
796 if ((str.charAt(index) & ~('x' ^ 'X')) == 'X')
811 throw new /*NumberFormat*/Exception("NumberFormatException");
813 long max = MAX_VALUE / radix;
814 // We can't directly write `max = (MAX_VALUE + 1) / radix'.
815 // So instead we fake it.
816 if (isNeg && MAX_VALUE % radix == radix - 1)
822 if (val < 0 || val > max)
823 throw new /*NumberFormat*/Exception("NumberFormatException");
825 ch = Character.digit(str.charAt(index++), radix);
826 val = val * radix + ch;
827 if (ch < 0 || (val < 0 && (! isNeg || val != MIN_VALUE)))
828 throw new /*NumberFormat*/Exception("NumberFormatException");
830 return isNeg ? -val : val;