Source for java.lang.Long

   1: /* Long.java -- object wrapper for long
   2:    Copyright (C) 1998, 1999, 2001, 2002, 2005  Free Software Foundation, Inc.
   3: 
   4: This file is part of GNU Classpath.
   5: 
   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.
  10: 
  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.
  15: 
  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.
  20: 
  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.
  25: 
  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. */
  37: 
  38: 
  39: package java.lang;
  40: 
  41: /**
  42:  * Instances of class <code>Long</code> represent primitive
  43:  * <code>long</code> values.
  44:  *
  45:  * Additionally, this class provides various helper functions and variables
  46:  * related to longs.
  47:  *
  48:  * @author Paul Fisher
  49:  * @author John Keiser
  50:  * @author Warren Levy
  51:  * @author Eric Blake (ebb9@email.byu.edu)
  52:  * @since 1.0
  53:  * @status updated to 1.4
  54:  */
  55: public final class Long extends Number implements Comparable
  56: {
  57:   /**
  58:    * Compatible with JDK 1.0.2+.
  59:    */
  60:   private static final long serialVersionUID = 4290774380558885855L;
  61: 
  62:   /**
  63:    * The minimum value a <code>long</code> can represent is
  64:    * -9223372036854775808L (or -2<sup>63</sup>).
  65:    */
  66:   public static final long MIN_VALUE = 0x8000000000000000L;
  67: 
  68:   /**
  69:    * The maximum value a <code>long</code> can represent is
  70:    * 9223372036854775807 (or 2<sup>63</sup> - 1).
  71:    */
  72:   public static final long MAX_VALUE = 0x7fffffffffffffffL;
  73: 
  74:   /**
  75:    * The primitive type <code>long</code> is represented by this
  76:    * <code>Class</code> object.
  77:    * @since 1.1
  78:    */
  79:   public static final Class TYPE = VMClassLoader.getPrimitiveClass ('J');
  80: 
  81:   /**
  82:    * The immutable value of this Long.
  83:    *
  84:    * @serial the wrapped long
  85:    */
  86:   private final long value;
  87: 
  88:   /**
  89:    * Create a <code>Long</code> object representing the value of the
  90:    * <code>long</code> argument.
  91:    *
  92:    * @param value the value to use
  93:    */
  94:   public Long(long value)
  95:   {
  96:     this.value = value;
  97:   }
  98: 
  99:   /**
 100:    * Create a <code>Long</code> object representing the value of the
 101:    * argument after conversion to a <code>long</code>.
 102:    *
 103:    * @param s the string to convert
 104:    * @throws NumberFormatException if the String does not contain a long
 105:    * @see #valueOf(String)
 106:    */
 107:   public Long(String s)
 108:   {
 109:     value = parseLong(s, 10, false);
 110:   }
 111: 
 112:   /**
 113:    * Converts the <code>long</code> to a <code>String</code> using
 114:    * the specified radix (base). If the radix exceeds
 115:    * <code>Character.MIN_RADIX</code> or <code>Character.MAX_RADIX</code>, 10
 116:    * is used instead. If the result is negative, the leading character is
 117:    * '-' ('\\u002D'). The remaining characters come from
 118:    * <code>Character.forDigit(digit, radix)</code> ('0'-'9','a'-'z').
 119:    *
 120:    * @param num the <code>long</code> to convert to <code>String</code>
 121:    * @param radix the radix (base) to use in the conversion
 122:    * @return the <code>String</code> representation of the argument
 123:    */
 124:   public static String toString(long num, int radix)
 125:   {
 126:     // Use the Integer toString for efficiency if possible.
 127:     if ((int) num == num)
 128:       return Integer.toString((int) num, radix);
 129: 
 130:     if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
 131:       radix = 10;
 132: 
 133:     // For negative numbers, print out the absolute value w/ a leading '-'.
 134:     // Use an array large enough for a binary number.
 135:     char[] buffer = new char[65];
 136:     int i = 65;
 137:     boolean isNeg = false;
 138:     if (num < 0)
 139:       {
 140:         isNeg = true;
 141:         num = -num;
 142: 
 143:         // When the value is MIN_VALUE, it overflows when made positive
 144:         if (num < 0)
 145:       {
 146:         buffer[--i] = digits[(int) (-(num + radix) % radix)];
 147:         num = -(num / radix);
 148:       }
 149:       }
 150: 
 151:     do
 152:       {
 153:         buffer[--i] = digits[(int) (num % radix)];
 154:         num /= radix;
 155:       }
 156:     while (num > 0);
 157: 
 158:     if (isNeg)
 159:       buffer[--i] = '-';
 160: 
 161:     // Package constructor avoids an array copy.
 162:     return new String(buffer, i, 65 - i, true);
 163:   }
 164: 
 165:   /**
 166:    * Converts the <code>long</code> to a <code>String</code> assuming it is
 167:    * unsigned in base 16.
 168:    *
 169:    * @param l the <code>long</code> to convert to <code>String</code>
 170:    * @return the <code>String</code> representation of the argument
 171:    */
 172:   public static String toHexString(long l)
 173:   {
 174:     return toUnsignedString(l, 4);
 175:   }
 176: 
 177:   /**
 178:    * Converts the <code>long</code> to a <code>String</code> assuming it is
 179:    * unsigned in base 8.
 180:    *
 181:    * @param l the <code>long</code> to convert to <code>String</code>
 182:    * @return the <code>String</code> representation of the argument
 183:    */
 184:   public static String toOctalString(long l)
 185:   {
 186:     return toUnsignedString(l, 3);
 187:   }
 188: 
 189:   /**
 190:    * Converts the <code>long</code> to a <code>String</code> assuming it is
 191:    * unsigned in base 2.
 192:    *
 193:    * @param l the <code>long</code> to convert to <code>String</code>
 194:    * @return the <code>String</code> representation of the argument
 195:    */
 196:   public static String toBinaryString(long l)
 197:   {
 198:     return toUnsignedString(l, 1);
 199:   }
 200: 
 201:   /**
 202:    * Converts the <code>long</code> to a <code>String</code> and assumes
 203:    * a radix of 10.
 204:    *
 205:    * @param num the <code>long</code> to convert to <code>String</code>
 206:    * @return the <code>String</code> representation of the argument
 207:    * @see #toString(long, int)
 208:    */
 209:   public static String toString(long num)
 210:   {
 211:     return toString(num, 10);
 212:   }
 213: 
 214:   /**
 215:    * Converts the specified <code>String</code> into an <code>int</code>
 216:    * using the specified radix (base). The string must not be <code>null</code>
 217:    * or empty. It may begin with an optional '-', which will negate the answer,
 218:    * provided that there are also valid digits. Each digit is parsed as if by
 219:    * <code>Character.digit(d, radix)</code>, and must be in the range
 220:    * <code>0</code> to <code>radix - 1</code>. Finally, the result must be
 221:    * within <code>MIN_VALUE</code> to <code>MAX_VALUE</code>, inclusive.
 222:    * Unlike Double.parseDouble, you may not have a leading '+'; and 'l' or
 223:    * 'L' as the last character is only valid in radices 22 or greater, where
 224:    * it is a digit and not a type indicator.
 225:    *
 226:    * @param str the <code>String</code> to convert
 227:    * @param radix the radix (base) to use in the conversion
 228:    * @return the <code>String</code> argument converted to <code>long</code>
 229:    * @throws NumberFormatException if <code>s</code> cannot be parsed as a
 230:    *         <code>long</code>
 231:    */
 232:   public static long parseLong(String str, int radix)
 233:   {
 234:     return parseLong(str, radix, false);
 235:   }
 236: 
 237:   /**
 238:    * Converts the specified <code>String</code> into a <code>long</code>.
 239:    * This function assumes a radix of 10.
 240:    *
 241:    * @param s the <code>String</code> to convert
 242:    * @return the <code>int</code> value of <code>s</code>
 243:    * @throws NumberFormatException if <code>s</code> cannot be parsed as a
 244:    *         <code>long</code>
 245:    * @see #parseLong(String, int)
 246:    */
 247:   public static long parseLong(String s)
 248:   {
 249:     return parseLong(s, 10, false);
 250:   }
 251: 
 252:   /**
 253:    * Creates a new <code>Long</code> object using the <code>String</code>
 254:    * and specified radix (base).
 255:    *
 256:    * @param s the <code>String</code> to convert
 257:    * @param radix the radix (base) to convert with
 258:    * @return the new <code>Long</code>
 259:    * @throws NumberFormatException if <code>s</code> cannot be parsed as a
 260:    *         <code>long</code>
 261:    * @see #parseLong(String, int)
 262:    */
 263:   public static Long valueOf(String s, int radix)
 264:   {
 265:     return new Long(parseLong(s, radix, false));
 266:   }
 267: 
 268:   /**
 269:    * Creates a new <code>Long</code> object using the <code>String</code>,
 270:    * assuming a radix of 10.
 271:    *
 272:    * @param s the <code>String</code> to convert
 273:    * @return the new <code>Long</code>
 274:    * @throws NumberFormatException if <code>s</code> cannot be parsed as a
 275:    *         <code>long</code>
 276:    * @see #Long(String)
 277:    * @see #parseLong(String)
 278:    */
 279:   public static Long valueOf(String s)
 280:   {
 281:     return new Long(parseLong(s, 10, false));
 282:   }
 283: 
 284:   /**
 285:    * Convert the specified <code>String</code> into a <code>Long</code>.
 286:    * The <code>String</code> may represent decimal, hexadecimal, or
 287:    * octal numbers.
 288:    *
 289:    * <p>The extended BNF grammar is as follows:<br>
 290:    * <pre>
 291:    * <em>DecodableString</em>:
 292:    *      ( [ <code>-</code> ] <em>DecimalNumber</em> )
 293:    *    | ( [ <code>-</code> ] ( <code>0x</code> | <code>0X</code>
 294:    *              | <code>#</code> ) <em>HexDigit</em> { <em>HexDigit</em> } )
 295:    *    | ( [ <code>-</code> ] <code>0</code> { <em>OctalDigit</em> } )
 296:    * <em>DecimalNumber</em>:
 297:    *        <em>DecimalDigit except '0'</em> { <em>DecimalDigit</em> }
 298:    * <em>DecimalDigit</em>:
 299:    *        <em>Character.digit(d, 10) has value 0 to 9</em>
 300:    * <em>OctalDigit</em>:
 301:    *        <em>Character.digit(d, 8) has value 0 to 7</em>
 302:    * <em>DecimalDigit</em>:
 303:    *        <em>Character.digit(d, 16) has value 0 to 15</em>
 304:    * </pre>
 305:    * Finally, the value must be in the range <code>MIN_VALUE</code> to
 306:    * <code>MAX_VALUE</code>, or an exception is thrown. Note that you cannot
 307:    * use a trailing 'l' or 'L', unlike in Java source code.
 308:    *
 309:    * @param str the <code>String</code> to interpret
 310:    * @return the value of the String as a <code>Long</code>
 311:    * @throws NumberFormatException if <code>s</code> cannot be parsed as a
 312:    *         <code>long</code>
 313:    * @throws NullPointerException if <code>s</code> is null
 314:    * @since 1.2
 315:    */
 316:   public static Long decode(String str)
 317:   {
 318:     return new Long(parseLong(str, 10, true));
 319:   }
 320: 
 321:   /**
 322:    * Return the value of this <code>Long</code> as a <code>byte</code>.
 323:    *
 324:    * @return the byte value
 325:    */
 326:   public byte byteValue()
 327:   {
 328:     return (byte) value;
 329:   }
 330: 
 331:   /**
 332:    * Return the value of this <code>Long</code> as a <code>short</code>.
 333:    *
 334:    * @return the short value
 335:    */
 336:   public short shortValue()
 337:   {
 338:     return (short) value;
 339:   }
 340: 
 341:   /**
 342:    * Return the value of this <code>Long</code> as an <code>int</code>.
 343:    *
 344:    * @return the int value
 345:    */
 346:   public int intValue()
 347:   {
 348:     return (int) value;
 349:   }
 350: 
 351:   /**
 352:    * Return the value of this <code>Long</code>.
 353:    *
 354:    * @return the long value
 355:    */
 356:   public long longValue()
 357:   {
 358:     return value;
 359:   }
 360: 
 361:   /**
 362:    * Return the value of this <code>Long</code> as a <code>float</code>.
 363:    *
 364:    * @return the float value
 365:    */
 366:   public float floatValue()
 367:   {
 368:     return value;
 369:   }
 370: 
 371:   /**
 372:    * Return the value of this <code>Long</code> as a <code>double</code>.
 373:    *
 374:    * @return the double value
 375:    */
 376:   public double doubleValue()
 377:   {
 378:     return value;
 379:   }
 380: 
 381:   /**
 382:    * Converts the <code>Long</code> value to a <code>String</code> and
 383:    * assumes a radix of 10.
 384:    *
 385:    * @return the <code>String</code> representation
 386:    */
 387:   public String toString()
 388:   {
 389:     return toString(value, 10);
 390:   }
 391: 
 392:   /**
 393:    * Return a hashcode representing this Object. <code>Long</code>'s hash
 394:    * code is calculated by <code>(int) (value ^ (value &gt;&gt; 32))</code>.
 395:    *
 396:    * @return this Object's hash code
 397:    */
 398:   public int hashCode()
 399:   {
 400:     return (int) (value ^ (value >>> 32));
 401:   }
 402: 
 403:   /**
 404:    * Returns <code>true</code> if <code>obj</code> is an instance of
 405:    * <code>Long</code> and represents the same long value.
 406:    *
 407:    * @param obj the object to compare
 408:    * @return whether these Objects are semantically equal
 409:    */
 410:   public boolean equals(Object obj)
 411:   {
 412:     return obj instanceof Long && value == ((Long) obj).value;
 413:   }
 414: 
 415:   /**
 416:    * Get the specified system property as a <code>Long</code>. The
 417:    * <code>decode()</code> method will be used to interpret the value of
 418:    * the property.
 419:    *
 420:    * @param nm the name of the system property
 421:    * @return the system property as a <code>Long</code>, or null if the
 422:    *         property is not found or cannot be decoded
 423:    * @throws SecurityException if accessing the system property is forbidden
 424:    * @see System#getProperty(String)
 425:    * @see #decode(String)
 426:    */
 427:   public static Long getLong(String nm)
 428:   {
 429:     return getLong(nm, null);
 430:   }
 431: 
 432:   /**
 433:    * Get the specified system property as a <code>Long</code>, or use a
 434:    * default <code>long</code> value if the property is not found or is not
 435:    * decodable. The <code>decode()</code> method will be used to interpret
 436:    * the value of the property.
 437:    *
 438:    * @param nm the name of the system property
 439:    * @param val the default value
 440:    * @return the value of the system property, or the default
 441:    * @throws SecurityException if accessing the system property is forbidden
 442:    * @see System#getProperty(String)
 443:    * @see #decode(String)
 444:    */
 445:   public static Long getLong(String nm, long val)
 446:   {
 447:     Long result = getLong(nm, null);
 448:     return result == null ? new Long(val) : result;
 449:   }
 450: 
 451:   /**
 452:    * Get the specified system property as a <code>Long</code>, or use a
 453:    * default <code>Long</code> value if the property is not found or is
 454:    * not decodable. The <code>decode()</code> method will be used to
 455:    * interpret the value of the property.
 456:    *
 457:    * @param nm the name of the system property
 458:    * @param def the default value
 459:    * @return the value of the system property, or the default
 460:    * @throws SecurityException if accessing the system property is forbidden
 461:    * @see System#getProperty(String)
 462:    * @see #decode(String)
 463:    */
 464:   public static Long getLong(String nm, Long def)
 465:   {
 466:     if (nm == null || "".equals(nm))
 467:       return def;
 468:     nm = System.getProperty(nm);
 469:     if (nm == null)
 470:       return def;
 471:     try
 472:       {
 473:         return decode(nm);
 474:       }
 475:     catch (NumberFormatException e)
 476:       {
 477:         return def;
 478:       }
 479:   }
 480: 
 481:   /**
 482:    * Compare two Longs numerically by comparing their <code>long</code>
 483:    * values. The result is positive if the first is greater, negative if the
 484:    * second is greater, and 0 if the two are equal.
 485:    *
 486:    * @param l the Long to compare
 487:    * @return the comparison
 488:    * @since 1.2
 489:    */
 490:   public int compareTo(Long l)
 491:   {
 492:     if (value == l.value)
 493:       return 0;
 494:     // Returns just -1 or 1 on inequality; doing math might overflow the long.
 495:     return value > l.value ? 1 : -1;
 496:   }
 497: 
 498:   /**
 499:    * Behaves like <code>compareTo(Long)</code> unless the Object
 500:    * is not a <code>Long</code>.
 501:    *
 502:    * @param o the object to compare
 503:    * @return the comparison
 504:    * @throws ClassCastException if the argument is not a <code>Long</code>
 505:    * @see #compareTo(Long)
 506:    * @see Comparable
 507:    * @since 1.2
 508:    */
 509:   public int compareTo(Object o)
 510:   {
 511:     return compareTo((Long) o);
 512:   }
 513: 
 514:   /**
 515:    * Helper for converting unsigned numbers to String.
 516:    *
 517:    * @param num the number
 518:    * @param exp log2(digit) (ie. 1, 3, or 4 for binary, oct, hex)
 519:    */
 520:   private static String toUnsignedString(long num, int exp)
 521:   {
 522:     // Use the Integer toUnsignedString for efficiency if possible.
 523:     // If NUM<0 then this particular optimization doesn't work
 524:     // properly.
 525:     if (num >= 0 && (int) num == num)
 526:       return Integer.toUnsignedString((int) num, exp);
 527: 
 528:     // Use an array large enough for a binary number.
 529:     int mask = (1 << exp) - 1;
 530:     char[] buffer = new char[64];
 531:     int i = 64;
 532:     do
 533:       {
 534:         buffer[--i] = digits[(int) num & mask];
 535:         num >>>= exp;
 536:       }
 537:     while (num != 0);
 538: 
 539:     // Package constructor avoids an array copy.
 540:     return new String(buffer, i, 64 - i, true);
 541:   }
 542: 
 543:   /**
 544:    * Helper for parsing longs.
 545:    *
 546:    * @param str the string to parse
 547:    * @param radix the radix to use, must be 10 if decode is true
 548:    * @param decode if called from decode
 549:    * @return the parsed long value
 550:    * @throws NumberFormatException if there is an error
 551:    * @throws NullPointerException if decode is true and str is null
 552:    * @see #parseLong(String, int)
 553:    * @see #decode(String)
 554:    */
 555:   private static long parseLong(String str, int radix, boolean decode)
 556:   {
 557:     if (! decode && str == null)
 558:       throw new NumberFormatException();
 559:     int index = 0;
 560:     int len = str.length();
 561:     boolean isNeg = false;
 562:     if (len == 0)
 563:       throw new NumberFormatException();
 564:     int ch = str.charAt(index);
 565:     if (ch == '-')
 566:       {
 567:         if (len == 1)
 568:           throw new NumberFormatException();
 569:         isNeg = true;
 570:         ch = str.charAt(++index);
 571:       }
 572:     if (decode)
 573:       {
 574:         if (ch == '0')
 575:           {
 576:             if (++index == len)
 577:               return 0;
 578:             if ((str.charAt(index) & ~('x' ^ 'X')) == 'X')
 579:               {
 580:                 radix = 16;
 581:                 index++;
 582:               }
 583:             else
 584:               radix = 8;
 585:           }
 586:         else if (ch == '#')
 587:           {
 588:             radix = 16;
 589:             index++;
 590:           }
 591:       }
 592:     if (index == len)
 593:       throw new NumberFormatException();
 594: 
 595:     long max = MAX_VALUE / radix;
 596:     // We can't directly write `max = (MAX_VALUE + 1) / radix'.
 597:     // So instead we fake it.
 598:     if (isNeg && MAX_VALUE % radix == radix - 1)
 599:       ++max;
 600: 
 601:     long val = 0;
 602:     while (index < len)
 603:       {
 604:     if (val < 0 || val > max)
 605:       throw new NumberFormatException();
 606: 
 607:         ch = Character.digit(str.charAt(index++), radix);
 608:         val = val * radix + ch;
 609:         if (ch < 0 || (val < 0 && (! isNeg || val != MIN_VALUE)))
 610:           throw new NumberFormatException();
 611:       }
 612:     return isNeg ? -val : val;
 613:   }
 614: }