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 * @since 1.0 055 * @status updated to 1.5 056 */ 057 public final class Long extends Number implements Comparable<Long> 058 { 059 /** 060 * Compatible with JDK 1.0.2+. 061 */ 062 private static final long serialVersionUID = 4290774380558885855L; 063 064 /** 065 * The minimum value a <code>long</code> can represent is 066 * -9223372036854775808L (or -2<sup>63</sup>). 067 */ 068 public static final long MIN_VALUE = 0x8000000000000000L; 069 070 /** 071 * The maximum value a <code>long</code> can represent is 072 * 9223372036854775807 (or 2<sup>63</sup> - 1). 073 */ 074 public static final long MAX_VALUE = 0x7fffffffffffffffL; 075 076 /** 077 * The primitive type <code>long</code> is represented by this 078 * <code>Class</code> object. 079 * @since 1.1 080 */ 081 public static final Class<Long> TYPE = (Class<Long>) VMClassLoader.getPrimitiveClass ('J'); 082 083 /** 084 * The number of bits needed to represent a <code>long</code>. 085 * @since 1.5 086 */ 087 public static final int SIZE = 64; 088 089 /** 090 * The immutable value of this Long. 091 * 092 * @serial the wrapped long 093 */ 094 private final long value; 095 096 /** 097 * Create a <code>Long</code> object representing the value of the 098 * <code>long</code> argument. 099 * 100 * @param value the value to use 101 */ 102 public Long(long value) 103 { 104 this.value = value; 105 } 106 107 /** 108 * Create a <code>Long</code> object representing the value of the 109 * argument after conversion to a <code>long</code>. 110 * 111 * @param s the string to convert 112 * @throws NumberFormatException if the String does not contain a long 113 * @see #valueOf(String) 114 */ 115 public Long(String s) 116 { 117 value = parseLong(s, 10, false); 118 } 119 120 /** 121 * Converts the <code>long</code> to a <code>String</code> using 122 * the specified radix (base). If the radix exceeds 123 * <code>Character.MIN_RADIX</code> or <code>Character.MAX_RADIX</code>, 10 124 * is used instead. If the result is negative, the leading character is 125 * '-' ('\\u002D'). The remaining characters come from 126 * <code>Character.forDigit(digit, radix)</code> ('0'-'9','a'-'z'). 127 * 128 * @param num the <code>long</code> to convert to <code>String</code> 129 * @param radix the radix (base) to use in the conversion 130 * @return the <code>String</code> representation of the argument 131 */ 132 public static String toString(long num, int radix) 133 { 134 // Use the Integer toString for efficiency if possible. 135 if ((int) num == num) 136 return Integer.toString((int) num, radix); 137 138 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) 139 radix = 10; 140 141 // For negative numbers, print out the absolute value w/ a leading '-'. 142 // Use an array large enough for a binary number. 143 char[] buffer = new char[65]; 144 int i = 65; 145 boolean isNeg = false; 146 if (num < 0) 147 { 148 isNeg = true; 149 num = -num; 150 151 // When the value is MIN_VALUE, it overflows when made positive 152 if (num < 0) 153 { 154 buffer[--i] = digits[(int) (-(num + radix) % radix)]; 155 num = -(num / radix); 156 } 157 } 158 159 do 160 { 161 buffer[--i] = digits[(int) (num % radix)]; 162 num /= radix; 163 } 164 while (num > 0); 165 166 if (isNeg) 167 buffer[--i] = '-'; 168 169 // Package constructor avoids an array copy. 170 return new String(buffer, i, 65 - i, true); 171 } 172 173 /** 174 * Converts the <code>long</code> to a <code>String</code> assuming it is 175 * unsigned in base 16. 176 * 177 * @param l the <code>long</code> to convert to <code>String</code> 178 * @return the <code>String</code> representation of the argument 179 */ 180 public static String toHexString(long l) 181 { 182 return toUnsignedString(l, 4); 183 } 184 185 /** 186 * Converts the <code>long</code> to a <code>String</code> assuming it is 187 * unsigned in base 8. 188 * 189 * @param l the <code>long</code> to convert to <code>String</code> 190 * @return the <code>String</code> representation of the argument 191 */ 192 public static String toOctalString(long l) 193 { 194 return toUnsignedString(l, 3); 195 } 196 197 /** 198 * Converts the <code>long</code> to a <code>String</code> assuming it is 199 * unsigned in base 2. 200 * 201 * @param l the <code>long</code> to convert to <code>String</code> 202 * @return the <code>String</code> representation of the argument 203 */ 204 public static String toBinaryString(long l) 205 { 206 return toUnsignedString(l, 1); 207 } 208 209 /** 210 * Converts the <code>long</code> to a <code>String</code> and assumes 211 * a radix of 10. 212 * 213 * @param num the <code>long</code> to convert to <code>String</code> 214 * @return the <code>String</code> representation of the argument 215 * @see #toString(long, int) 216 */ 217 public static String toString(long num) 218 { 219 return toString(num, 10); 220 } 221 222 /** 223 * Converts the specified <code>String</code> into an <code>int</code> 224 * using the specified radix (base). The string must not be <code>null</code> 225 * or empty. It may begin with an optional '-', which will negate the answer, 226 * provided that there are also valid digits. Each digit is parsed as if by 227 * <code>Character.digit(d, radix)</code>, and must be in the range 228 * <code>0</code> to <code>radix - 1</code>. Finally, the result must be 229 * within <code>MIN_VALUE</code> to <code>MAX_VALUE</code>, inclusive. 230 * Unlike Double.parseDouble, you may not have a leading '+'; and 'l' or 231 * 'L' as the last character is only valid in radices 22 or greater, where 232 * it is a digit and not a type indicator. 233 * 234 * @param str the <code>String</code> to convert 235 * @param radix the radix (base) to use in the conversion 236 * @return the <code>String</code> argument converted to <code>long</code> 237 * @throws NumberFormatException if <code>s</code> cannot be parsed as a 238 * <code>long</code> 239 */ 240 public static long parseLong(String str, int radix) 241 { 242 return parseLong(str, radix, false); 243 } 244 245 /** 246 * Converts the specified <code>String</code> into a <code>long</code>. 247 * This function assumes a radix of 10. 248 * 249 * @param s the <code>String</code> to convert 250 * @return the <code>int</code> value of <code>s</code> 251 * @throws NumberFormatException if <code>s</code> cannot be parsed as a 252 * <code>long</code> 253 * @see #parseLong(String, int) 254 */ 255 public static long parseLong(String s) 256 { 257 return parseLong(s, 10, false); 258 } 259 260 /** 261 * Creates a new <code>Long</code> object using the <code>String</code> 262 * and specified radix (base). 263 * 264 * @param s the <code>String</code> to convert 265 * @param radix the radix (base) to convert with 266 * @return the new <code>Long</code> 267 * @throws NumberFormatException if <code>s</code> cannot be parsed as a 268 * <code>long</code> 269 * @see #parseLong(String, int) 270 */ 271 public static Long valueOf(String s, int radix) 272 { 273 return new Long(parseLong(s, radix, false)); 274 } 275 276 /** 277 * Creates a new <code>Long</code> object using the <code>String</code>, 278 * assuming a radix of 10. 279 * 280 * @param s the <code>String</code> to convert 281 * @return the new <code>Long</code> 282 * @throws NumberFormatException if <code>s</code> cannot be parsed as a 283 * <code>long</code> 284 * @see #Long(String) 285 * @see #parseLong(String) 286 */ 287 public static Long valueOf(String s) 288 { 289 return new Long(parseLong(s, 10, false)); 290 } 291 292 /** 293 * Returns a <code>Long</code> object wrapping the value. 294 * 295 * @param val the value to wrap 296 * @return the <code>Long</code> 297 * @since 1.5 298 */ 299 public static synchronized Long valueOf(long val) 300 { 301 // We aren't required to cache here. We could, though perhaps we 302 // ought to consider that as an empirical question. 303 return new Long(val); 304 } 305 306 /** 307 * Convert the specified <code>String</code> into a <code>Long</code>. 308 * The <code>String</code> may represent decimal, hexadecimal, or 309 * octal numbers. 310 * 311 * <p>The extended BNF grammar is as follows:<br> 312 * <pre> 313 * <em>DecodableString</em>: 314 * ( [ <code>-</code> ] <em>DecimalNumber</em> ) 315 * | ( [ <code>-</code> ] ( <code>0x</code> | <code>0X</code> 316 * | <code>#</code> ) <em>HexDigit</em> { <em>HexDigit</em> } ) 317 * | ( [ <code>-</code> ] <code>0</code> { <em>OctalDigit</em> } ) 318 * <em>DecimalNumber</em>: 319 * <em>DecimalDigit except '0'</em> { <em>DecimalDigit</em> } 320 * <em>DecimalDigit</em>: 321 * <em>Character.digit(d, 10) has value 0 to 9</em> 322 * <em>OctalDigit</em>: 323 * <em>Character.digit(d, 8) has value 0 to 7</em> 324 * <em>DecimalDigit</em>: 325 * <em>Character.digit(d, 16) has value 0 to 15</em> 326 * </pre> 327 * Finally, the value must be in the range <code>MIN_VALUE</code> to 328 * <code>MAX_VALUE</code>, or an exception is thrown. Note that you cannot 329 * use a trailing 'l' or 'L', unlike in Java source code. 330 * 331 * @param str the <code>String</code> to interpret 332 * @return the value of the String as a <code>Long</code> 333 * @throws NumberFormatException if <code>s</code> cannot be parsed as a 334 * <code>long</code> 335 * @throws NullPointerException if <code>s</code> is null 336 * @since 1.2 337 */ 338 public static Long decode(String str) 339 { 340 return new Long(parseLong(str, 10, true)); 341 } 342 343 /** 344 * Return the value of this <code>Long</code> as a <code>byte</code>. 345 * 346 * @return the byte value 347 */ 348 public byte byteValue() 349 { 350 return (byte) value; 351 } 352 353 /** 354 * Return the value of this <code>Long</code> as a <code>short</code>. 355 * 356 * @return the short value 357 */ 358 public short shortValue() 359 { 360 return (short) value; 361 } 362 363 /** 364 * Return the value of this <code>Long</code> as an <code>int</code>. 365 * 366 * @return the int value 367 */ 368 public int intValue() 369 { 370 return (int) value; 371 } 372 373 /** 374 * Return the value of this <code>Long</code>. 375 * 376 * @return the long value 377 */ 378 public long longValue() 379 { 380 return value; 381 } 382 383 /** 384 * Return the value of this <code>Long</code> as a <code>float</code>. 385 * 386 * @return the float value 387 */ 388 public float floatValue() 389 { 390 return value; 391 } 392 393 /** 394 * Return the value of this <code>Long</code> as a <code>double</code>. 395 * 396 * @return the double value 397 */ 398 public double doubleValue() 399 { 400 return value; 401 } 402 403 /** 404 * Converts the <code>Long</code> value to a <code>String</code> and 405 * assumes a radix of 10. 406 * 407 * @return the <code>String</code> representation 408 */ 409 public String toString() 410 { 411 return toString(value, 10); 412 } 413 414 /** 415 * Return a hashcode representing this Object. <code>Long</code>'s hash 416 * code is calculated by <code>(int) (value ^ (value >> 32))</code>. 417 * 418 * @return this Object's hash code 419 */ 420 public int hashCode() 421 { 422 return (int) (value ^ (value >>> 32)); 423 } 424 425 /** 426 * Returns <code>true</code> if <code>obj</code> is an instance of 427 * <code>Long</code> and represents the same long value. 428 * 429 * @param obj the object to compare 430 * @return whether these Objects are semantically equal 431 */ 432 public boolean equals(Object obj) 433 { 434 return obj instanceof Long && value == ((Long) obj).value; 435 } 436 437 /** 438 * Get the specified system property as a <code>Long</code>. The 439 * <code>decode()</code> method will be used to interpret the value of 440 * the property. 441 * 442 * @param nm the name of the system property 443 * @return the system property as a <code>Long</code>, or null if the 444 * property is not found or cannot be decoded 445 * @throws SecurityException if accessing the system property is forbidden 446 * @see System#getProperty(String) 447 * @see #decode(String) 448 */ 449 public static Long getLong(String nm) 450 { 451 return getLong(nm, null); 452 } 453 454 /** 455 * Get the specified system property as a <code>Long</code>, or use a 456 * default <code>long</code> value if the property is not found or is not 457 * decodable. The <code>decode()</code> method will be used to interpret 458 * the value of the property. 459 * 460 * @param nm the name of the system property 461 * @param val the default value 462 * @return the value of the system property, or the default 463 * @throws SecurityException if accessing the system property is forbidden 464 * @see System#getProperty(String) 465 * @see #decode(String) 466 */ 467 public static Long getLong(String nm, long val) 468 { 469 Long result = getLong(nm, null); 470 return result == null ? new Long(val) : result; 471 } 472 473 /** 474 * Get the specified system property as a <code>Long</code>, or use a 475 * default <code>Long</code> value if the property is not found or is 476 * not decodable. The <code>decode()</code> method will be used to 477 * interpret the value of the property. 478 * 479 * @param nm the name of the system property 480 * @param def the default value 481 * @return the value of the system property, or the default 482 * @throws SecurityException if accessing the system property is forbidden 483 * @see System#getProperty(String) 484 * @see #decode(String) 485 */ 486 public static Long getLong(String nm, Long def) 487 { 488 if (nm == null || "".equals(nm)) 489 return def; 490 nm = System.getProperty(nm); 491 if (nm == null) 492 return def; 493 try 494 { 495 return decode(nm); 496 } 497 catch (NumberFormatException e) 498 { 499 return def; 500 } 501 } 502 503 /** 504 * Compare two Longs numerically by comparing their <code>long</code> 505 * values. The result is positive if the first is greater, negative if the 506 * second is greater, and 0 if the two are equal. 507 * 508 * @param l the Long to compare 509 * @return the comparison 510 * @since 1.2 511 */ 512 public int compareTo(Long l) 513 { 514 if (value == l.value) 515 return 0; 516 // Returns just -1 or 1 on inequality; doing math might overflow the long. 517 return value > l.value ? 1 : -1; 518 } 519 520 /** 521 * Return the number of bits set in x. 522 * @param x value to examine 523 * @since 1.5 524 */ 525 public static int bitCount(long x) 526 { 527 // Successively collapse alternating bit groups into a sum. 528 x = ((x >> 1) & 0x5555555555555555L) + (x & 0x5555555555555555L); 529 x = ((x >> 2) & 0x3333333333333333L) + (x & 0x3333333333333333L); 530 int v = (int) ((x >>> 32) + x); 531 v = ((v >> 4) & 0x0f0f0f0f) + (v & 0x0f0f0f0f); 532 v = ((v >> 8) & 0x00ff00ff) + (v & 0x00ff00ff); 533 return ((v >> 16) & 0x0000ffff) + (v & 0x0000ffff); 534 } 535 536 /** 537 * Rotate x to the left by distance bits. 538 * @param x the value to rotate 539 * @param distance the number of bits by which to rotate 540 * @since 1.5 541 */ 542 public static long rotateLeft(long x, int distance) 543 { 544 // This trick works because the shift operators implicitly mask 545 // the shift count. 546 return (x << distance) | (x >>> - distance); 547 } 548 549 /** 550 * Rotate x to the right by distance bits. 551 * @param x the value to rotate 552 * @param distance the number of bits by which to rotate 553 * @since 1.5 554 */ 555 public static long rotateRight(long x, int distance) 556 { 557 // This trick works because the shift operators implicitly mask 558 // the shift count. 559 return (x << - distance) | (x >>> distance); 560 } 561 562 /** 563 * Find the highest set bit in value, and return a new value 564 * with only that bit set. 565 * @param value the value to examine 566 * @since 1.5 567 */ 568 public static long highestOneBit(long value) 569 { 570 value |= value >>> 1; 571 value |= value >>> 2; 572 value |= value >>> 4; 573 value |= value >>> 8; 574 value |= value >>> 16; 575 value |= value >>> 32; 576 return value ^ (value >>> 1); 577 } 578 579 /** 580 * Return the number of leading zeros in value. 581 * @param value the value to examine 582 * @since 1.5 583 */ 584 public static int numberOfLeadingZeros(long value) 585 { 586 value |= value >>> 1; 587 value |= value >>> 2; 588 value |= value >>> 4; 589 value |= value >>> 8; 590 value |= value >>> 16; 591 value |= value >>> 32; 592 return bitCount(~value); 593 } 594 595 /** 596 * Find the lowest set bit in value, and return a new value 597 * with only that bit set. 598 * @param value the value to examine 599 * @since 1.5 600 */ 601 public static long lowestOneBit(long value) 602 { 603 // Classic assembly trick. 604 return value & - value; 605 } 606 607 /** 608 * Find the number of trailing zeros in value. 609 * @param value the value to examine 610 * @since 1.5 611 */ 612 public static int numberOfTrailingZeros(long value) 613 { 614 return bitCount((value & -value) - 1); 615 } 616 617 /** 618 * Return 1 if x is positive, -1 if it is negative, and 0 if it is 619 * zero. 620 * @param x the value to examine 621 * @since 1.5 622 */ 623 public static int signum(long x) 624 { 625 return x < 0 ? -1 : (x > 0 ? 1 : 0); 626 } 627 628 /** 629 * Reverse the bytes in val. 630 * @since 1.5 631 */ 632 public static long reverseBytes(long val) 633 { 634 int hi = Integer.reverseBytes((int) val); 635 int lo = Integer.reverseBytes((int) (val >>> 32)); 636 return (((long) hi) << 32) | lo; 637 } 638 639 /** 640 * Reverse the bits in val. 641 * @since 1.5 642 */ 643 public static long reverse(long val) 644 { 645 long hi = Integer.reverse((int) val) & 0xffffffffL; 646 long lo = Integer.reverse((int) (val >>> 32)) & 0xffffffffL; 647 return (hi << 32) | lo; 648 } 649 650 /** 651 * Helper for converting unsigned numbers to String. 652 * 653 * @param num the number 654 * @param exp log2(digit) (ie. 1, 3, or 4 for binary, oct, hex) 655 */ 656 private static String toUnsignedString(long num, int exp) 657 { 658 // Use the Integer toUnsignedString for efficiency if possible. 659 // If NUM<0 then this particular optimization doesn't work 660 // properly. 661 if (num >= 0 && (int) num == num) 662 return Integer.toUnsignedString((int) num, exp); 663 664 // Use an array large enough for a binary number. 665 int mask = (1 << exp) - 1; 666 char[] buffer = new char[64]; 667 int i = 64; 668 do 669 { 670 buffer[--i] = digits[(int) num & mask]; 671 num >>>= exp; 672 } 673 while (num != 0); 674 675 // Package constructor avoids an array copy. 676 return new String(buffer, i, 64 - i, true); 677 } 678 679 /** 680 * Helper for parsing longs. 681 * 682 * @param str the string to parse 683 * @param radix the radix to use, must be 10 if decode is true 684 * @param decode if called from decode 685 * @return the parsed long value 686 * @throws NumberFormatException if there is an error 687 * @throws NullPointerException if decode is true and str is null 688 * @see #parseLong(String, int) 689 * @see #decode(String) 690 */ 691 private static long parseLong(String str, int radix, boolean decode) 692 { 693 if (! decode && str == null) 694 throw new NumberFormatException(); 695 int index = 0; 696 int len = str.length(); 697 boolean isNeg = false; 698 if (len == 0) 699 throw new NumberFormatException(); 700 int ch = str.charAt(index); 701 if (ch == '-') 702 { 703 if (len == 1) 704 throw new NumberFormatException(); 705 isNeg = true; 706 ch = str.charAt(++index); 707 } 708 if (decode) 709 { 710 if (ch == '0') 711 { 712 if (++index == len) 713 return 0; 714 if ((str.charAt(index) & ~('x' ^ 'X')) == 'X') 715 { 716 radix = 16; 717 index++; 718 } 719 else 720 radix = 8; 721 } 722 else if (ch == '#') 723 { 724 radix = 16; 725 index++; 726 } 727 } 728 if (index == len) 729 throw new NumberFormatException(); 730 731 long max = MAX_VALUE / radix; 732 // We can't directly write `max = (MAX_VALUE + 1) / radix'. 733 // So instead we fake it. 734 if (isNeg && MAX_VALUE % radix == radix - 1) 735 ++max; 736 737 long val = 0; 738 while (index < len) 739 { 740 if (val < 0 || val > max) 741 throw new NumberFormatException(); 742 743 ch = Character.digit(str.charAt(index++), radix); 744 val = val * radix + ch; 745 if (ch < 0 || (val < 0 && (! isNeg || val != MIN_VALUE))) 746 throw new NumberFormatException(); 747 } 748 return isNeg ? -val : val; 749 } 750 }