1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package java.lang; 19 20 /** 21 * The wrapper for the primitive type {@code long}. 22 * <p> 23 * As with the specification, this implementation relies on code laid out in <a 24 * href="http://www.hackersdelight.org/">Henry S. Warren, Jr.'s Hacker's 25 * Delight, (Addison Wesley, 2002)</a> as well as <a 26 * href="http://aggregate.org/MAGIC/">The Aggregate's Magic Algorithms</a>. 27 * 28 * @see java.lang.Number 29 * @since 1.0 30 */ 31 public final class Long extends Number implements Comparable<Long> { 32 33 private static final long serialVersionUID = 4290774380558885855L; 34 35 /** 36 * The value which the receiver represents. 37 */ 38 private final long value; 39 40 /** 41 * Constant for the maximum {@code long} value, 2<sup>63</sup>-1. 42 */ 43 public static final long MAX_VALUE = 0x7FFFFFFFFFFFFFFFL; 44 45 /** 46 * Constant for the minimum {@code long} value, -2<sup>63</sup>. 47 */ 48 public static final long MIN_VALUE = 0x8000000000000000L; 49 50 /** 51 * The {@link Class} object that represents the primitive type {@code long}. 52 */ 53 @SuppressWarnings("unchecked") 54 public static final Class<Long> TYPE = (Class<Long>) new long[0].getClass() 55 .getComponentType(); 56 57 // Note: This can't be set to "long.class", since *that* is 58 // defined to be "java.lang.Long.TYPE"; 59 60 /** 61 * Constant for the number of bits needed to represent a {@code long} in 62 * two's complement form. 63 * 64 * @since 1.5 65 */ 66 public static final int SIZE = 64; 67 68 69 /** 70 * Constructs a new {@code Long} with the specified primitive long value. 71 * 72 * @param value 73 * the primitive long value to store in the new instance. 74 */ Long(long value)75 public Long(long value) { 76 this.value = value; 77 } 78 79 /** 80 * Constructs a new {@code Long} from the specified string. 81 * 82 * @param string 83 * the string representation of a long value. 84 * @throws NumberFormatException 85 * if {@code string} can not be decoded into a long value. 86 * @see #parseLong(String) 87 */ Long(String string)88 public Long(String string) throws NumberFormatException { 89 this(parseLong(string)); 90 } 91 92 @Override byteValue()93 public byte byteValue() { 94 return (byte) value; 95 } 96 97 /** 98 * Compares this object to the specified long object to determine their 99 * relative order. 100 * 101 * @param object 102 * the long object to compare this object to. 103 * @return a negative value if the value of this long is less than the value 104 * of {@code object}; 0 if the value of this long and the value of 105 * {@code object} are equal; a positive value if the value of this 106 * long is greater than the value of {@code object}. 107 * @see java.lang.Comparable 108 * @since 1.2 109 */ compareTo(Long object)110 public int compareTo(Long object) { 111 return value > object.value ? 1 : (value < object.value ? -1 : 0); 112 } 113 114 /** 115 * Parses the specified string and returns a {@code Long} instance if the 116 * string can be decoded into a long value. The string may be an optional 117 * minus sign "-" followed by a hexadecimal ("0x..." or "#..."), octal 118 * ("0..."), or decimal ("...") representation of a long. 119 * 120 * @param string 121 * a string representation of a long value. 122 * @return a {@code Long} containing the value represented by {@code string}. 123 * @throws NumberFormatException 124 * if {@code string} can not be parsed as a long value. 125 */ decode(String string)126 public static Long decode(String string) throws NumberFormatException { 127 int length = string.length(), i = 0; 128 if (length == 0) { 129 throw new NumberFormatException(); 130 } 131 char firstDigit = string.charAt(i); 132 boolean negative = firstDigit == '-'; 133 if (negative) { 134 if (length == 1) { 135 throw new NumberFormatException(string); 136 } 137 firstDigit = string.charAt(++i); 138 } 139 140 int base = 10; 141 if (firstDigit == '0') { 142 if (++i == length) { 143 return valueOf(0L); 144 } 145 if ((firstDigit = string.charAt(i)) == 'x' || firstDigit == 'X') { 146 if (i == length) { 147 throw new NumberFormatException(string); 148 } 149 i++; 150 base = 16; 151 } else { 152 base = 8; 153 } 154 } else if (firstDigit == '#') { 155 if (i == length) { 156 throw new NumberFormatException(string); 157 } 158 i++; 159 base = 16; 160 } 161 162 long result = parse(string, i, base, negative); 163 return valueOf(result); 164 } 165 166 @Override doubleValue()167 public double doubleValue() { 168 return value; 169 } 170 171 /** 172 * Compares this instance with the specified object and indicates if they 173 * are equal. In order to be equal, {@code o} must be an instance of 174 * {@code Long} and have the same long value as this object. 175 * 176 * @param o 177 * the object to compare this long with. 178 * @return {@code true} if the specified object is equal to this 179 * {@code Long}; {@code false} otherwise. 180 */ 181 @Override equals(Object o)182 public boolean equals(Object o) { 183 return (o instanceof Long) 184 && (value == ((Long) o).value); 185 } 186 187 @Override floatValue()188 public float floatValue() { 189 return value; 190 } 191 192 /** 193 * Returns the {@code Long} value of the system property identified by 194 * {@code string}. Returns {@code null} if {@code string} is {@code null} 195 * or empty, if the property can not be found or if its value can not be 196 * parsed as a long. 197 * 198 * @param string 199 * the name of the requested system property. 200 * @return the requested property's value as a {@code Long} or {@code null}. 201 */ getLong(String string)202 public static Long getLong(String string) { 203 if (string == null || string.length() == 0) { 204 return null; 205 } 206 String prop = System.getProperty(string); 207 if (prop == null) { 208 return null; 209 } 210 try { 211 return decode(prop); 212 } catch (NumberFormatException ex) { 213 return null; 214 } 215 } 216 217 /** 218 * Returns the {@code Long} value of the system property identified by 219 * {@code string}. Returns the specified default value if {@code string} is 220 * {@code null} or empty, if the property can not be found or if its value 221 * can not be parsed as a long. 222 * 223 * @param string 224 * the name of the requested system property. 225 * @param defaultValue 226 * the default value that is returned if there is no long system 227 * property with the requested name. 228 * @return the requested property's value as a {@code Long} or the default 229 * value. 230 */ getLong(String string, long defaultValue)231 public static Long getLong(String string, long defaultValue) { 232 if (string == null || string.length() == 0) { 233 return valueOf(defaultValue); 234 } 235 String prop = System.getProperty(string); 236 if (prop == null) { 237 return valueOf(defaultValue); 238 } 239 try { 240 return decode(prop); 241 } catch (NumberFormatException ex) { 242 return valueOf(defaultValue); 243 } 244 } 245 246 /** 247 * Returns the {@code Long} value of the system property identified by 248 * {@code string}. Returns the specified default value if {@code string} is 249 * {@code null} or empty, if the property can not be found or if its value 250 * can not be parsed as a long. 251 * 252 * @param string 253 * the name of the requested system property. 254 * @param defaultValue 255 * the default value that is returned if there is no long system 256 * property with the requested name. 257 * @return the requested property's value as a {@code Long} or the default 258 * value. 259 */ getLong(String string, Long defaultValue)260 public static Long getLong(String string, Long defaultValue) { 261 if (string == null || string.length() == 0) { 262 return defaultValue; 263 } 264 String prop = System.getProperty(string); 265 if (prop == null) { 266 return defaultValue; 267 } 268 try { 269 return decode(prop); 270 } catch (NumberFormatException ex) { 271 return defaultValue; 272 } 273 } 274 275 @Override hashCode()276 public int hashCode() { 277 return (int) (value ^ (value >>> 32)); 278 } 279 280 @Override intValue()281 public int intValue() { 282 return (int) value; 283 } 284 285 /** 286 * Gets the primitive value of this long. 287 * 288 * @return this object's primitive value. 289 */ 290 @Override longValue()291 public long longValue() { 292 return value; 293 } 294 295 /** 296 * Parses the specified string as a signed decimal long value. The ASCII 297 * character \u002d ('-') is recognized as the minus sign. 298 * 299 * @param string 300 * the string representation of a long value. 301 * @return the primitive long value represented by {@code string}. 302 * @throws NumberFormatException 303 * if {@code string} is {@code null}, has a length of zero or 304 * can not be parsed as a long value. 305 */ parseLong(String string)306 public static long parseLong(String string) throws NumberFormatException { 307 return parseLong(string, 10); 308 } 309 310 /** 311 * Parses the specified string as a signed long value using the specified 312 * radix. The ASCII character \u002d ('-') is recognized as the minus sign. 313 * 314 * @param string 315 * the string representation of a long value. 316 * @param radix 317 * the radix to use when parsing. 318 * @return the primitive long value represented by {@code string} using 319 * {@code radix}. 320 * @throws NumberFormatException 321 * if {@code string} is {@code null} or has a length of zero, 322 * {@code radix < Character.MIN_RADIX}, 323 * {@code radix > Character.MAX_RADIX}, or if {@code string} 324 * can not be parsed as a long value. 325 */ parseLong(String string, int radix)326 public static long parseLong(String string, int radix) 327 throws NumberFormatException { 328 if (string == null || radix < Character.MIN_RADIX 329 || radix > Character.MAX_RADIX) { 330 throw new NumberFormatException(); 331 } 332 int length = string.length(), i = 0; 333 if (length == 0) { 334 throw new NumberFormatException(string); 335 } 336 boolean negative = string.charAt(i) == '-'; 337 if (negative && ++i == length) { 338 throw new NumberFormatException(string); 339 } 340 341 return parse(string, i, radix, negative); 342 } 343 parse(String string, int offset, int radix, boolean negative)344 private static long parse(String string, int offset, int radix, 345 boolean negative) { 346 long max = Long.MIN_VALUE / radix; 347 long result = 0, length = string.length(); 348 while (offset < length) { 349 int digit = Character.digit(string.charAt(offset++), radix); 350 if (digit == -1) { 351 throw new NumberFormatException(string); 352 } 353 if (max > result) { 354 throw new NumberFormatException(string); 355 } 356 long next = result * radix - digit; 357 if (next > result) { 358 throw new NumberFormatException(string); 359 } 360 result = next; 361 } 362 if (!negative) { 363 result = -result; 364 if (result < 0) { 365 throw new NumberFormatException(string); 366 } 367 } 368 return result; 369 } 370 371 @Override shortValue()372 public short shortValue() { 373 return (short) value; 374 } 375 376 /** 377 * Converts the specified long value into its binary string representation. 378 * The returned string is a concatenation of '0' and '1' characters. 379 * 380 * @param l 381 * the long value to convert. 382 * @return the binary string representation of {@code l}. 383 */ toBinaryString(long l)384 public static String toBinaryString(long l) { 385 int count = 1; 386 long j = l; 387 388 if (l < 0) { 389 count = 64; 390 } else { 391 while ((j >>= 1) != 0) { 392 count++; 393 } 394 } 395 396 char[] buffer = new char[count]; 397 do { 398 buffer[--count] = (char) ((l & 1) + '0'); 399 l >>= 1; 400 } while (count > 0); 401 return new String(0, buffer.length, buffer); 402 } 403 404 /** 405 * Converts the specified long value into its hexadecimal string 406 * representation. The returned string is a concatenation of characters from 407 * '0' to '9' and 'a' to 'f'. 408 * 409 * @param l 410 * the long value to convert. 411 * @return the hexadecimal string representation of {@code l}. 412 */ toHexString(long l)413 public static String toHexString(long l) { 414 int count = 1; 415 long j = l; 416 417 if (l < 0) { 418 count = 16; 419 } else { 420 while ((j >>= 4) != 0) { 421 count++; 422 } 423 } 424 425 char[] buffer = new char[count]; 426 do { 427 int t = (int) (l & 15); 428 if (t > 9) { 429 t = t - 10 + 'a'; 430 } else { 431 t += '0'; 432 } 433 buffer[--count] = (char) t; 434 l >>= 4; 435 } while (count > 0); 436 return new String(0, buffer.length, buffer); 437 } 438 439 /** 440 * Converts the specified long value into its octal string representation. 441 * The returned string is a concatenation of characters from '0' to '7'. 442 * 443 * @param l 444 * the long value to convert. 445 * @return the octal string representation of {@code l}. 446 */ toOctalString(long l)447 public static String toOctalString(long l) { 448 int count = 1; 449 long j = l; 450 451 if (l < 0) { 452 count = 22; 453 } else { 454 while ((j >>>= 3) != 0) { 455 count++; 456 } 457 } 458 459 char[] buffer = new char[count]; 460 do { 461 buffer[--count] = (char) ((l & 7) + '0'); 462 l >>>= 3; 463 } while (count > 0); 464 return new String(0, buffer.length, buffer); 465 } 466 467 @Override toString()468 public String toString() { 469 return Long.toString(value); 470 } 471 472 /** 473 * Converts the specified long value into its decimal string representation. 474 * The returned string is a concatenation of a minus sign if the number is 475 * negative and characters from '0' to '9'. 476 * 477 * @param l 478 * the long to convert. 479 * @return the decimal string representation of {@code l}. 480 */ toString(long l)481 public static String toString(long l) { 482 return toString(l, 10); 483 } 484 485 /** 486 * Converts the specified long value into a string representation based on 487 * the specified radix. The returned string is a concatenation of a minus 488 * sign if the number is negative and characters from '0' to '9' and 'a' to 489 * 'z', depending on the radix. If {@code radix} is not in the interval 490 * defined by {@code Character.MIN_RADIX} and {@code Character.MAX_RADIX} 491 * then 10 is used as the base for the conversion. 492 * 493 * @param l 494 * the long to convert. 495 * @param radix 496 * the base to use for the conversion. 497 * @return the string representation of {@code l}. 498 */ toString(long l, int radix)499 public static String toString(long l, int radix) { 500 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { 501 radix = 10; 502 } 503 if (l == 0) { 504 return "0"; //$NON-NLS-1$ 505 } 506 507 int count = 2; 508 long j = l; 509 boolean negative = l < 0; 510 if (!negative) { 511 count = 1; 512 j = -l; 513 } 514 while ((l /= radix) != 0) { 515 count++; 516 } 517 518 char[] buffer = new char[count]; 519 do { 520 int ch = 0 - (int) (j % radix); 521 if (ch > 9) { 522 ch = ch - 10 + 'a'; 523 } else { 524 ch += '0'; 525 } 526 buffer[--count] = (char) ch; 527 } while ((j /= radix) != 0); 528 if (negative) { 529 buffer[0] = '-'; 530 } 531 return new String(0, buffer.length, buffer); 532 } 533 534 /** 535 * Parses the specified string as a signed decimal long value. 536 * 537 * @param string 538 * the string representation of a long value. 539 * @return a {@code Long} instance containing the long value represented by 540 * {@code string}. 541 * @throws NumberFormatException 542 * if {@code string} is {@code null}, has a length of zero or 543 * can not be parsed as a long value. 544 * @see #parseLong(String) 545 */ valueOf(String string)546 public static Long valueOf(String string) throws NumberFormatException { 547 return valueOf(parseLong(string)); 548 } 549 550 /** 551 * Parses the specified string as a signed long value using the specified 552 * radix. 553 * 554 * @param string 555 * the string representation of a long value. 556 * @param radix 557 * the radix to use when parsing. 558 * @return a {@code Long} instance containing the long value represented by 559 * {@code string} using {@code radix}. 560 * @throws NumberFormatException 561 * if {@code string} is {@code null} or has a length of zero, 562 * {@code radix < Character.MIN_RADIX}, 563 * {@code radix > Character.MAX_RADIX}, or if {@code string} 564 * can not be parsed as a long value. 565 * @see #parseLong(String, int) 566 */ valueOf(String string, int radix)567 public static Long valueOf(String string, int radix) 568 throws NumberFormatException { 569 return valueOf(parseLong(string, radix)); 570 } 571 572 /** 573 * Determines the highest (leftmost) bit of the specified long value that is 574 * 1 and returns the bit mask value for that bit. This is also referred to 575 * as the Most Significant 1 Bit. Returns zero if the specified long is 576 * zero. 577 * 578 * @param lng 579 * the long to examine. 580 * @return the bit mask indicating the highest 1 bit in {@code lng}. 581 * @since 1.5 582 */ highestOneBit(long lng)583 public static long highestOneBit(long lng) { 584 lng |= (lng >> 1); 585 lng |= (lng >> 2); 586 lng |= (lng >> 4); 587 lng |= (lng >> 8); 588 lng |= (lng >> 16); 589 lng |= (lng >> 32); 590 return (lng & ~(lng >>> 1)); 591 } 592 593 /** 594 * Determines the lowest (rightmost) bit of the specified long value that is 595 * 1 and returns the bit mask value for that bit. This is also referred to 596 * as the Least Significant 1 Bit. Returns zero if the specified long is 597 * zero. 598 * 599 * @param lng 600 * the long to examine. 601 * @return the bit mask indicating the lowest 1 bit in {@code lng}. 602 * @since 1.5 603 */ lowestOneBit(long lng)604 public static long lowestOneBit(long lng) { 605 return (lng & (-lng)); 606 } 607 608 /** 609 * Determines the number of leading zeros in the specified long value prior 610 * to the {@link #highestOneBit(long) highest one bit}. 611 * 612 * @param lng 613 * the long to examine. 614 * @return the number of leading zeros in {@code lng}. 615 * @since 1.5 616 */ numberOfLeadingZeros(long lng)617 public static int numberOfLeadingZeros(long lng) { 618 lng |= lng >> 1; 619 lng |= lng >> 2; 620 lng |= lng >> 4; 621 lng |= lng >> 8; 622 lng |= lng >> 16; 623 lng |= lng >> 32; 624 return bitCount(~lng); 625 } 626 627 /** 628 * Determines the number of trailing zeros in the specified long value after 629 * the {@link #lowestOneBit(long) lowest one bit}. 630 * 631 * @param lng 632 * the long to examine. 633 * @return the number of trailing zeros in {@code lng}. 634 * @since 1.5 635 */ numberOfTrailingZeros(long lng)636 public static int numberOfTrailingZeros(long lng) { 637 return bitCount((lng & -lng) - 1); 638 } 639 640 /** 641 * Counts the number of 1 bits in the specified long value; this is also 642 * referred to as population count. 643 * 644 * @param lng 645 * the long to examine. 646 * @return the number of 1 bits in {@code lng}. 647 * @since 1.5 648 */ bitCount(long lng)649 public static int bitCount(long lng) { 650 lng = (lng & 0x5555555555555555L) + ((lng >> 1) & 0x5555555555555555L); 651 lng = (lng & 0x3333333333333333L) + ((lng >> 2) & 0x3333333333333333L); 652 // adjust for 64-bit integer 653 int i = (int) ((lng >>> 32) + lng); 654 i = (i & 0x0F0F0F0F) + ((i >> 4) & 0x0F0F0F0F); 655 i = (i & 0x00FF00FF) + ((i >> 8) & 0x00FF00FF); 656 i = (i & 0x0000FFFF) + ((i >> 16) & 0x0000FFFF); 657 return i; 658 } 659 660 /** 661 * Rotates the bits of the specified long value to the left by the specified 662 * number of bits. 663 * 664 * @param lng 665 * the long value to rotate left. 666 * @param distance 667 * the number of bits to rotate. 668 * @return the rotated value. 669 * @since 1.5 670 */ rotateLeft(long lng, int distance)671 public static long rotateLeft(long lng, int distance) { 672 if (distance == 0) { 673 return lng; 674 } 675 /* 676 * According to JLS3, 15.19, the right operand of a shift is always 677 * implicitly masked with 0x3F, which the negation of 'distance' is 678 * taking advantage of. 679 */ 680 return ((lng << distance) | (lng >>> (-distance))); 681 } 682 683 /** 684 * <p> 685 * Rotates the bits of the specified long value to the right by the 686 * specified number of bits. 687 * 688 * @param lng 689 * the long value to rotate right. 690 * @param distance 691 * the number of bits to rotate. 692 * @return the rotated value. 693 * @since 1.5 694 */ rotateRight(long lng, int distance)695 public static long rotateRight(long lng, int distance) { 696 if (distance == 0) { 697 return lng; 698 } 699 /* 700 * According to JLS3, 15.19, the right operand of a shift is always 701 * implicitly masked with 0x3F, which the negation of 'distance' is 702 * taking advantage of. 703 */ 704 return ((lng >>> distance) | (lng << (-distance))); 705 } 706 707 /** 708 * Reverses the order of the bytes of the specified long value. 709 * 710 * @param lng 711 * the long value for which to reverse the byte order. 712 * @return the reversed value. 713 * @since 1.5 714 */ reverseBytes(long lng)715 public static long reverseBytes(long lng) { 716 long b7 = lng >>> 56; 717 long b6 = (lng >>> 40) & 0xFF00L; 718 long b5 = (lng >>> 24) & 0xFF0000L; 719 long b4 = (lng >>> 8) & 0xFF000000L; 720 long b3 = (lng & 0xFF000000L) << 8; 721 long b2 = (lng & 0xFF0000L) << 24; 722 long b1 = (lng & 0xFF00L) << 40; 723 long b0 = lng << 56; 724 return (b0 | b1 | b2 | b3 | b4 | b5 | b6 | b7); 725 } 726 727 /** 728 * Reverses the order of the bits of the specified long value. 729 * 730 * @param lng 731 * the long value for which to reverse the bit order. 732 * @return the reversed value. 733 * @since 1.5 734 */ reverse(long lng)735 public static long reverse(long lng) { 736 // From Hacker's Delight, 7-1, Figure 7-1 737 lng = (lng & 0x5555555555555555L) << 1 | (lng >> 1) 738 & 0x5555555555555555L; 739 lng = (lng & 0x3333333333333333L) << 2 | (lng >> 2) 740 & 0x3333333333333333L; 741 lng = (lng & 0x0F0F0F0F0F0F0F0FL) << 4 | (lng >> 4) 742 & 0x0F0F0F0F0F0F0F0FL; 743 return reverseBytes(lng); 744 } 745 746 /** 747 * Returns the value of the {@code signum} function for the specified long 748 * value. 749 * 750 * @param lng 751 * the long value to check. 752 * @return -1 if {@code lng} is negative, 1 if {@code lng} is positive, 0 if 753 * {@code lng} is zero. 754 * @since 1.5 755 */ signum(long lng)756 public static int signum(long lng) { 757 return (lng == 0 ? 0 : (lng < 0 ? -1 : 1)); 758 } 759 760 /** 761 * Returns a {@code Long} instance for the specified long value. 762 * <p> 763 * If it is not necessary to get a new {@code Long} instance, it is 764 * recommended to use this method instead of the constructor, since it 765 * maintains a cache of instances which may result in better performance. 766 * 767 * @param lng 768 * the long value to store in the instance. 769 * @return a {@code Long} instance containing {@code lng}. 770 * @since 1.5 771 */ valueOf(long lng)772 public static Long valueOf(long lng) { 773 if (lng < -128 || lng > 127) { 774 return new Long(lng); 775 } 776 return valueOfCache.CACHE[128+(int)lng]; 777 } 778 779 static class valueOfCache { 780 /** 781 * <p> 782 * A cache of instances used by {@link Long#valueOf(long)} and auto-boxing. 783 */ 784 static final Long[] CACHE = new Long[256]; 785 786 static { 787 for(int i=-128; i<=127; i++) { 788 CACHE[i+128] = new Long(i); 789 } 790 } 791 } 792 } 793