001    /* Long.java -- object wrapper for long
002       Copyright (C) 1998, 1999, 2001, 2002, 2004, 2005 Free Software Foundation, Inc.
003    
004    This file is part of GNU Classpath.
005    
006    GNU Classpath is free software; you can redistribute it and/or modify
007    it under the terms of the GNU General Public License as published by
008    the Free Software Foundation; either version 2, or (at your option)
009    any later version.
010    
011    GNU Classpath is distributed in the hope that it will be useful, but
012    WITHOUT ANY WARRANTY; without even the implied warranty of
013    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014    General Public License for more details.
015    
016    You should have received a copy of the GNU General Public License
017    along with GNU Classpath; see the file COPYING.  If not, write to the
018    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
019    02110-1301 USA.
020    
021    Linking this library statically or dynamically with other modules is
022    making a combined work based on this library.  Thus, the terms and
023    conditions of the GNU General Public License cover the whole
024    combination.
025    
026    As a special exception, the copyright holders of this library give you
027    permission to link this library with independent modules to produce an
028    executable, regardless of the license terms of these independent
029    modules, and to copy and distribute the resulting executable under
030    terms of your choice, provided that you also meet, for each linked
031    independent module, the terms and conditions of the license of that
032    module.  An independent module is a module which is not derived from
033    or based on this library.  If you modify this library, you may extend
034    this exception to your version of the library, but you are not
035    obligated to do so.  If you do not wish to do so, delete this
036    exception statement from your version. */
037    
038    
039    package java.lang;
040    
041    /**
042     * Instances of class <code>Long</code> represent primitive
043     * <code>long</code> values.
044     *
045     * Additionally, this class provides various helper functions and variables
046     * related to longs.
047     *
048     * @author Paul Fisher
049     * @author John Keiser
050     * @author Warren Levy
051     * @author Eric Blake (ebb9@email.byu.edu)
052     * @author Tom Tromey (tromey@redhat.com)
053     * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
054     * @author Ian Rogers
055     * @since 1.0
056     * @status updated to 1.5
057     */
058    public final class Long extends Number implements Comparable<Long>
059    {
060      /**
061       * Compatible with JDK 1.0.2+.
062       */
063      private static final long serialVersionUID = 4290774380558885855L;
064    
065      /**
066       * The minimum value a <code>long</code> can represent is
067       * -9223372036854775808L (or -2<sup>63</sup>).
068       */
069      public static final long MIN_VALUE = 0x8000000000000000L;
070    
071      /**
072       * The maximum value a <code>long</code> can represent is
073       * 9223372036854775807 (or 2<sup>63</sup> - 1).
074       */
075      public static final long MAX_VALUE = 0x7fffffffffffffffL;
076    
077      /**
078       * The primitive type <code>long</code> is represented by this
079       * <code>Class</code> object.
080       * @since 1.1
081       */
082      public static final Class<Long> TYPE = (Class<Long>) VMClassLoader.getPrimitiveClass ('J');
083    
084      /**
085       * The number of bits needed to represent a <code>long</code>.
086       * @since 1.5
087       */
088      public static final int SIZE = 64;
089    
090      // This caches some Long values, and is used by boxing
091      // conversions via valueOf().  We cache at least -128..127;
092      // these constants control how much we actually cache.
093      private static final int MIN_CACHE = -128;
094      private static final int MAX_CACHE = 127;
095      private static final Long[] longCache = new Long[MAX_CACHE - MIN_CACHE + 1];
096      static
097      {
098        for (int i=MIN_CACHE; i <= MAX_CACHE; i++)
099          longCache[i - MIN_CACHE] = new Long(i);
100      }
101    
102      /**
103       * The immutable value of this Long.
104       *
105       * @serial the wrapped long
106       */
107      private final long value;
108    
109      /**
110       * Create a <code>Long</code> object representing the value of the
111       * <code>long</code> argument.
112       *
113       * @param value the value to use
114       */
115      public Long(long value)
116      {
117        this.value = value;
118      }
119    
120      /**
121       * Create a <code>Long</code> object representing the value of the
122       * argument after conversion to a <code>long</code>.
123       *
124       * @param s the string to convert
125       * @throws NumberFormatException if the String does not contain a long
126       * @see #valueOf(String)
127       */
128      public Long(String s)
129      {
130        value = parseLong(s, 10, false);
131      }
132    
133      /**
134       * Return the size of a string large enough to hold the given number
135       *
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
139       */
140      private static int stringSize(long num, int radix) {
141        int exp;
142        if (radix < 4)
143          {
144            exp = 1;
145          }
146        else if (radix < 8)
147          {
148            exp = 2;
149          }
150        else if (radix < 16)
151          {
152            exp = 3;
153          }
154        else if (radix < 32)
155          {
156            exp = 4;
157          }
158        else
159          {
160            exp = 5;
161          }
162        int size=0;
163        do
164          {
165            num >>>= exp;
166            size++;
167          }
168        while(num != 0);
169        return size;
170      }
171    
172      /**
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').
179       *
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
183       */
184      public static String toString(long num, int radix)
185      {
186        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
187          radix = 10;
188    
189        // Is the value negative?
190        boolean isNeg = num < 0;
191    
192        // Is the string a single character?
193        if (!isNeg && num < radix)
194          return new String(digits, (int)num, 1, true);
195    
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)
202          {
203            num = -num;
204    
205            // When the value is MIN_VALUE, it overflows when made positive
206            if (num < 0)
207              {
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);
212              }
213            else
214              {
215                i = size = stringSize(num, radix) + 1;
216                buffer = new char[size];
217              }
218          }
219        else
220          {
221            i = size = stringSize(num, radix);
222            buffer = new char[size];
223          }
224    
225        do
226          {
227            buffer[--i] = digits[(int) (num % radix)];
228            num /= radix;
229          }
230        while (num > 0);
231    
232        if (isNeg)
233          buffer[--i] = '-';
234    
235        // Package constructor avoids an array copy.
236        return new String(buffer, i, size - i, true);
237      }
238    
239      /**
240       * Converts the <code>long</code> to a <code>String</code> assuming it is
241       * unsigned in base 16.
242       *
243       * @param l the <code>long</code> to convert to <code>String</code>
244       * @return the <code>String</code> representation of the argument
245       */
246      public static String toHexString(long l)
247      {
248        return toUnsignedString(l, 4);
249      }
250    
251      /**
252       * Converts the <code>long</code> to a <code>String</code> assuming it is
253       * unsigned in base 8.
254       *
255       * @param l the <code>long</code> to convert to <code>String</code>
256       * @return the <code>String</code> representation of the argument
257       */
258      public static String toOctalString(long l)
259      {
260        return toUnsignedString(l, 3);
261      }
262    
263      /**
264       * Converts the <code>long</code> to a <code>String</code> assuming it is
265       * unsigned in base 2.
266       *
267       * @param l the <code>long</code> to convert to <code>String</code>
268       * @return the <code>String</code> representation of the argument
269       */
270      public static String toBinaryString(long l)
271      {
272        return toUnsignedString(l, 1);
273      }
274    
275      /**
276       * Converts the <code>long</code> to a <code>String</code> and assumes
277       * a radix of 10.
278       *
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)
282       */
283      public static String toString(long num)
284      {
285        return toString(num, 10);
286      }
287    
288      /**
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.
299       *
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>
305       */
306      public static long parseLong(String str, int radix)
307      {
308        return parseLong(str, radix, false);
309      }
310    
311      /**
312       * Converts the specified <code>String</code> into a <code>long</code>.
313       * This function assumes a radix of 10.
314       *
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)
320       */
321      public static long parseLong(String s)
322      {
323        return parseLong(s, 10, false);
324      }
325    
326      /**
327       * Creates a new <code>Long</code> object using the <code>String</code>
328       * and specified radix (base).
329       *
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)
336       */
337      public static Long valueOf(String s, int radix)
338      {
339        return valueOf(parseLong(s, radix, false));
340      }
341    
342      /**
343       * Creates a new <code>Long</code> object using the <code>String</code>,
344       * assuming a radix of 10.
345       *
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)
352       */
353      public static Long valueOf(String s)
354      {
355        return valueOf(parseLong(s, 10, false));
356      }
357    
358      /**
359       * Returns a <code>Long</code> object wrapping the value.
360       *
361       * @param val the value to wrap
362       * @return the <code>Long</code>
363       * @since 1.5
364       */
365      public static Long valueOf(long val)
366      {
367        if (val < MIN_CACHE || val > MAX_CACHE)
368          return new Long(val);
369        else
370          return longCache[((int)val) - MIN_CACHE];
371      }
372    
373      /**
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.
377       *
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.
397       *
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
404       */
405      public static Long decode(String str)
406      {
407        return valueOf(parseLong(str, 10, true));
408      }
409    
410      /**
411       * Return the value of this <code>Long</code> as a <code>byte</code>.
412       *
413       * @return the byte value
414       */
415      public byte byteValue()
416      {
417        return (byte) value;
418      }
419    
420      /**
421       * Return the value of this <code>Long</code> as a <code>short</code>.
422       *
423       * @return the short value
424       */
425      public short shortValue()
426      {
427        return (short) value;
428      }
429    
430      /**
431       * Return the value of this <code>Long</code> as an <code>int</code>.
432       *
433       * @return the int value
434       */
435      public int intValue()
436      {
437        return (int) value;
438      }
439    
440      /**
441       * Return the value of this <code>Long</code>.
442       *
443       * @return the long value
444       */
445      public long longValue()
446      {
447        return value;
448      }
449    
450      /**
451       * Return the value of this <code>Long</code> as a <code>float</code>.
452       *
453       * @return the float value
454       */
455      public float floatValue()
456      {
457        return value;
458      }
459    
460      /**
461       * Return the value of this <code>Long</code> as a <code>double</code>.
462       *
463       * @return the double value
464       */
465      public double doubleValue()
466      {
467        return value;
468      }
469    
470      /**
471       * Converts the <code>Long</code> value to a <code>String</code> and
472       * assumes a radix of 10.
473       *
474       * @return the <code>String</code> representation
475       */
476      public String toString()
477      {
478        return toString(value, 10);
479      }
480    
481      /**
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>.
484       *
485       * @return this Object's hash code
486       */
487      public int hashCode()
488      {
489        return (int) (value ^ (value >>> 32));
490      }
491    
492      /**
493       * Returns <code>true</code> if <code>obj</code> is an instance of
494       * <code>Long</code> and represents the same long value.
495       *
496       * @param obj the object to compare
497       * @return whether these Objects are semantically equal
498       */
499      public boolean equals(Object obj)
500      {
501        return obj instanceof Long && value == ((Long) obj).value;
502      }
503    
504      /**
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.
508       *
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)
515       */
516      public static Long getLong(String nm)
517      {
518        return getLong(nm, null);
519      }
520    
521      /**
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.
526       *
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)
533       */
534      public static Long getLong(String nm, long val)
535      {
536        Long result = getLong(nm, null);
537        return result == null ? valueOf(val) : result;
538      }
539    
540      /**
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.
545       *
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)
552       */
553      public static Long getLong(String nm, Long def)
554      {
555        if (nm == null || "".equals(nm))
556          return def;
557        nm = System.getProperty(nm);
558        if (nm == null)
559          return def;
560        try
561          {
562            return decode(nm);
563          }
564        catch (NumberFormatException e)
565          {
566            return def;
567          }
568      }
569    
570      /**
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.
574       *
575       * @param l the Long to compare
576       * @return the comparison
577       * @since 1.2
578       */
579      public int compareTo(Long l)
580      {
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;
585      }
586    
587      /**
588       * Return the number of bits set in x.
589       * @param x value to examine
590       * @since 1.5
591       */
592      public static int bitCount(long x)
593      {
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);
601      }
602    
603      /**
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
608       */
609      public static long rotateLeft(long x, int distance)
610      {
611        // This trick works because the shift operators implicitly mask
612        // the shift count.
613        return (x << distance) | (x >>> - distance);
614      }
615    
616      /**
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
621       */
622      public static long rotateRight(long x, int distance)
623      {
624        // This trick works because the shift operators implicitly mask
625        // the shift count.
626        return (x << - distance) | (x >>> distance);
627      }
628    
629      /**
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
634       */
635      public static long highestOneBit(long value)
636      {
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);
644      }
645    
646      /**
647       * Return the number of leading zeros in value.
648       * @param value the value to examine
649       * @since 1.5
650       */
651      public static int numberOfLeadingZeros(long value)
652      {
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);
660      }
661    
662      /**
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
667       */
668      public static long lowestOneBit(long value)
669      {
670        // Classic assembly trick.
671        return value & - value;
672      }
673    
674      /**
675       * Find the number of trailing zeros in value.
676       * @param value the value to examine
677       * @since 1.5
678       */
679      public static int numberOfTrailingZeros(long value)
680      {
681        return bitCount((value & -value) - 1);
682      }
683    
684      /**
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
689       */
690      public static int signum(long x)
691      {
692        return (int) ((x >> 63) | (-x >>> 63));
693    
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.
698    
699        // Hacker's Delight, Section 2-7
700      }
701    
702      /**
703       * Reverse the bytes in val.
704       * @since 1.5
705       */
706      public static long reverseBytes(long val)
707      {
708        int hi = Integer.reverseBytes((int) val);
709        int lo = Integer.reverseBytes((int) (val >>> 32));
710        return (((long) hi) << 32) | lo;
711      }
712    
713      /**
714       * Reverse the bits in val.
715       * @since 1.5
716       */
717      public static long reverse(long val)
718      {
719        long hi = Integer.reverse((int) val) & 0xffffffffL;
720        long lo = Integer.reverse((int) (val >>> 32)) & 0xffffffffL;
721        return (hi << 32) | lo;
722      }
723    
724      /**
725       * Helper for converting unsigned numbers to String.
726       *
727       * @param num the number
728       * @param exp log2(digit) (ie. 1, 3, or 4 for binary, oct, hex)
729       */
730      private static String toUnsignedString(long num, int exp)
731      {
732        // Compute string length
733        int size = 1;
734        long copy = num >>> exp;
735        while (copy != 0)
736          {
737            size++;
738            copy >>>= exp;
739          }
740        // Quick path for single character strings
741        if (size == 1)
742          return new String(digits, (int)num, 1, true);
743    
744        // Encode into buffer
745        int mask = (1 << exp) - 1;
746        char[] buffer = new char[size];
747        int i = size;
748        do
749          {
750            buffer[--i] = digits[(int) num & mask];
751            num >>>= exp;
752          }
753        while (num != 0);
754    
755        // Package constructor avoids an array copy.
756        return new String(buffer, i, size - i, true);
757      }
758    
759      /**
760       * Helper for parsing longs.
761       *
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)
770       */
771      private static long parseLong(String str, int radix, boolean decode)
772      {
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 == '-')
782          {
783            if (len == 1)
784              throw new NumberFormatException();
785            isNeg = true;
786            ch = str.charAt(++index);
787          }
788        if (decode)
789          {
790            if (ch == '0')
791              {
792                if (++index == len)
793                  return 0;
794                if ((str.charAt(index) & ~('x' ^ 'X')) == 'X')
795                  {
796                    radix = 16;
797                    index++;
798                  }
799                else
800                  radix = 8;
801              }
802            else if (ch == '#')
803              {
804                radix = 16;
805                index++;
806              }
807          }
808        if (index == len)
809          throw new NumberFormatException();
810    
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;
816    
817        long val = 0;
818        while (index < len)
819          {
820            if (val < 0 || val > max)
821              throw new NumberFormatException();
822    
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();
827          }
828        return isNeg ? -val : val;
829      }
830    }