2 * Copyright (c) 1994, 2009, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
29 * The {@code Long} class wraps a value of the primitive type {@code
30 * long} in an object. An object of type {@code Long} contains a
31 * single field whose type is {@code long}.
33 * <p> In addition, this class provides several methods for converting
34 * a {@code long} to a {@code String} and a {@code String} to a {@code
35 * long}, as well as other constants and methods useful when dealing
36 * with a {@code long}.
38 * <p>Implementation note: The implementations of the "bit twiddling"
39 * methods (such as {@link #highestOneBit(long) highestOneBit} and
40 * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are
41 * based on material from Henry S. Warren, Jr.'s <i>Hacker's
42 * Delight</i>, (Addison Wesley, 2002).
45 * @author Arthur van Hoff
47 * @author Joseph D. Darcy
50 public final class Long extends Number implements Comparable<Long> {
52 * A constant holding the minimum value a {@code long} can
53 * have, -2<sup>63</sup>.
55 public static final long MIN_VALUE = 0x8000000000000000L;
58 * A constant holding the maximum value a {@code long} can
59 * have, 2<sup>63</sup>-1.
61 public static final long MAX_VALUE = 0x7fffffffffffffffL;
64 * The {@code Class} instance representing the primitive type
69 public static final Class<Long> TYPE = (Class<Long>) Class.getPrimitiveClass("long");
72 * Returns a string representation of the first argument in the
73 * radix specified by the second argument.
75 * <p>If the radix is smaller than {@code Character.MIN_RADIX}
76 * or larger than {@code Character.MAX_RADIX}, then the radix
77 * {@code 10} is used instead.
79 * <p>If the first argument is negative, the first element of the
80 * result is the ASCII minus sign {@code '-'}
81 * (<code>'\u002d'</code>). If the first argument is not
82 * negative, no sign character appears in the result.
84 * <p>The remaining characters of the result represent the magnitude
85 * of the first argument. If the magnitude is zero, it is
86 * represented by a single zero character {@code '0'}
87 * (<code>'\u0030'</code>); otherwise, the first character of
88 * the representation of the magnitude will not be the zero
89 * character. The following ASCII characters are used as digits:
92 * {@code 0123456789abcdefghijklmnopqrstuvwxyz}
95 * These are <code>'\u0030'</code> through
96 * <code>'\u0039'</code> and <code>'\u0061'</code> through
97 * <code>'\u007a'</code>. If {@code radix} is
98 * <var>N</var>, then the first <var>N</var> of these characters
99 * are used as radix-<var>N</var> digits in the order shown. Thus,
100 * the digits for hexadecimal (radix 16) are
101 * {@code 0123456789abcdef}. If uppercase letters are
102 * desired, the {@link java.lang.String#toUpperCase()} method may
103 * be called on the result:
106 * {@code Long.toString(n, 16).toUpperCase()}
109 * @param i a {@code long} to be converted to a string.
110 * @param radix the radix to use in the string representation.
111 * @return a string representation of the argument in the specified radix.
112 * @see java.lang.Character#MAX_RADIX
113 * @see java.lang.Character#MIN_RADIX
115 public static String toString(long i, int radix) {
116 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
120 char[] buf = new char[65];
122 boolean negative = (i < 0);
128 while (i <= -radix) {
129 buf[charPos--] = Integer.digits[(int)(-(i % radix))];
132 buf[charPos] = Integer.digits[(int)(-i)];
135 buf[--charPos] = '-';
138 return new String(buf, charPos, (65 - charPos));
142 * Returns a string representation of the {@code long}
143 * argument as an unsigned integer in base 16.
145 * <p>The unsigned {@code long} value is the argument plus
146 * 2<sup>64</sup> if the argument is negative; otherwise, it is
147 * equal to the argument. This value is converted to a string of
148 * ASCII digits in hexadecimal (base 16) with no extra
149 * leading {@code 0}s. If the unsigned magnitude is zero, it
150 * is represented by a single zero character {@code '0'}
151 * (<code>'\u0030'</code>); otherwise, the first character of
152 * the representation of the unsigned magnitude will not be the
153 * zero character. The following characters are used as
154 * hexadecimal digits:
157 * {@code 0123456789abcdef}
160 * These are the characters <code>'\u0030'</code> through
161 * <code>'\u0039'</code> and <code>'\u0061'</code> through
162 * <code>'\u0066'</code>. If uppercase letters are desired,
163 * the {@link java.lang.String#toUpperCase()} method may be called
167 * {@code Long.toHexString(n).toUpperCase()}
170 * @param i a {@code long} to be converted to a string.
171 * @return the string representation of the unsigned {@code long}
172 * value represented by the argument in hexadecimal
176 public static String toHexString(long i) {
177 return toUnsignedString(i, 4);
181 * Returns a string representation of the {@code long}
182 * argument as an unsigned integer in base 8.
184 * <p>The unsigned {@code long} value is the argument plus
185 * 2<sup>64</sup> if the argument is negative; otherwise, it is
186 * equal to the argument. This value is converted to a string of
187 * ASCII digits in octal (base 8) with no extra leading
190 * <p>If the unsigned magnitude is zero, it is represented by a
191 * single zero character {@code '0'}
192 * (<code>'\u0030'</code>); otherwise, the first character of
193 * the representation of the unsigned magnitude will not be the
194 * zero character. The following characters are used as octal
201 * These are the characters <code>'\u0030'</code> through
202 * <code>'\u0037'</code>.
204 * @param i a {@code long} to be converted to a string.
205 * @return the string representation of the unsigned {@code long}
206 * value represented by the argument in octal (base 8).
209 public static String toOctalString(long i) {
210 return toUnsignedString(i, 3);
214 * Returns a string representation of the {@code long}
215 * argument as an unsigned integer in base 2.
217 * <p>The unsigned {@code long} value is the argument plus
218 * 2<sup>64</sup> if the argument is negative; otherwise, it is
219 * equal to the argument. This value is converted to a string of
220 * ASCII digits in binary (base 2) with no extra leading
221 * {@code 0}s. If the unsigned magnitude is zero, it is
222 * represented by a single zero character {@code '0'}
223 * (<code>'\u0030'</code>); otherwise, the first character of
224 * the representation of the unsigned magnitude will not be the
225 * zero character. The characters {@code '0'}
226 * (<code>'\u0030'</code>) and {@code '1'}
227 * (<code>'\u0031'</code>) are used as binary digits.
229 * @param i a {@code long} to be converted to a string.
230 * @return the string representation of the unsigned {@code long}
231 * value represented by the argument in binary (base 2).
234 public static String toBinaryString(long i) {
235 return toUnsignedString(i, 1);
239 * Convert the integer to an unsigned number.
241 private static String toUnsignedString(long i, int shift) {
242 char[] buf = new char[64];
244 int radix = 1 << shift;
245 long mask = radix - 1;
247 buf[--charPos] = Integer.digits[(int)(i & mask)];
250 return new String(buf, charPos, (64 - charPos));
254 * Returns a {@code String} object representing the specified
255 * {@code long}. The argument is converted to signed decimal
256 * representation and returned as a string, exactly as if the
257 * argument and the radix 10 were given as arguments to the {@link
258 * #toString(long, int)} method.
260 * @param i a {@code long} to be converted.
261 * @return a string representation of the argument in base 10.
263 public static String toString(long i) {
264 if (i == Long.MIN_VALUE)
265 return "-9223372036854775808";
266 int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
267 char[] buf = new char[size];
268 getChars(i, size, buf);
269 return new String(0, size, buf);
273 * Places characters representing the integer i into the
274 * character array buf. The characters are placed into
275 * the buffer backwards starting with the least significant
276 * digit at the specified index (exclusive), and working
277 * backwards from there.
279 * Will fail if i == Long.MIN_VALUE
281 static void getChars(long i, int index, char[] buf) {
292 // Get 2 digits/iteration using longs until quotient fits into an int
293 while (i > Integer.MAX_VALUE) {
295 // really: r = i - (q * 100);
296 r = (int)(i - ((q << 6) + (q << 5) + (q << 2)));
298 buf[--charPos] = Integer.DigitOnes[r];
299 buf[--charPos] = Integer.DigitTens[r];
302 // Get 2 digits/iteration using ints
305 while (i2 >= 65536) {
307 // really: r = i2 - (q * 100);
308 r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
310 buf[--charPos] = Integer.DigitOnes[r];
311 buf[--charPos] = Integer.DigitTens[r];
314 // Fall thru to fast mode for smaller numbers
315 // assert(i2 <= 65536, i2);
317 q2 = (i2 * 52429) >>> (16+3);
318 r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ...
319 buf[--charPos] = Integer.digits[r];
324 buf[--charPos] = sign;
328 // Requires positive x
329 static int stringSize(long x) {
331 for (int i=1; i<19; i++) {
340 * Parses the string argument as a signed {@code long} in the
341 * radix specified by the second argument. The characters in the
342 * string must all be digits of the specified radix (as determined
343 * by whether {@link java.lang.Character#digit(char, int)} returns
344 * a nonnegative value), except that the first character may be an
345 * ASCII minus sign {@code '-'} (<code>'\u002D'</code>) to
346 * indicate a negative value or an ASCII plus sign {@code '+'}
347 * (<code>'\u002B'</code>) to indicate a positive value. The
348 * resulting {@code long} value is returned.
350 * <p>Note that neither the character {@code L}
351 * (<code>'\u004C'</code>) nor {@code l}
352 * (<code>'\u006C'</code>) is permitted to appear at the end
353 * of the string as a type indicator, as would be permitted in
354 * Java programming language source code - except that either
355 * {@code L} or {@code l} may appear as a digit for a
356 * radix greater than 22.
358 * <p>An exception of type {@code NumberFormatException} is
359 * thrown if any of the following situations occurs:
362 * <li>The first argument is {@code null} or is a string of
365 * <li>The {@code radix} is either smaller than {@link
366 * java.lang.Character#MIN_RADIX} or larger than {@link
367 * java.lang.Character#MAX_RADIX}.
369 * <li>Any character of the string is not a digit of the specified
370 * radix, except that the first character may be a minus sign
371 * {@code '-'} (<code>'\u002d'</code>) or plus sign {@code
372 * '+'} (<code>'\u002B'</code>) provided that the string is
373 * longer than length 1.
375 * <li>The value represented by the string is not a value of type
381 * parseLong("0", 10) returns 0L
382 * parseLong("473", 10) returns 473L
383 * parseLong("+42", 10) returns 42L
384 * parseLong("-0", 10) returns 0L
385 * parseLong("-FF", 16) returns -255L
386 * parseLong("1100110", 2) returns 102L
387 * parseLong("99", 8) throws a NumberFormatException
388 * parseLong("Hazelnut", 10) throws a NumberFormatException
389 * parseLong("Hazelnut", 36) returns 1356099454469L
390 * </pre></blockquote>
392 * @param s the {@code String} containing the
393 * {@code long} representation to be parsed.
394 * @param radix the radix to be used while parsing {@code s}.
395 * @return the {@code long} represented by the string argument in
396 * the specified radix.
397 * @throws NumberFormatException if the string does not contain a
398 * parsable {@code long}.
400 public static long parseLong(String s, int radix)
401 throws NumberFormatException
404 throw new NumberFormatException("null");
407 if (radix < Character.MIN_RADIX) {
408 throw new NumberFormatException("radix " + radix +
409 " less than Character.MIN_RADIX");
411 if (radix > Character.MAX_RADIX) {
412 throw new NumberFormatException("radix " + radix +
413 " greater than Character.MAX_RADIX");
417 boolean negative = false;
418 int i = 0, len = s.length();
419 long limit = -Long.MAX_VALUE;
424 char firstChar = s.charAt(0);
425 if (firstChar < '0') { // Possible leading "+" or "-"
426 if (firstChar == '-') {
428 limit = Long.MIN_VALUE;
429 } else if (firstChar != '+')
430 throw NumberFormatException.forInputString(s);
432 if (len == 1) // Cannot have lone "+" or "-"
433 throw NumberFormatException.forInputString(s);
436 multmin = limit / radix;
438 // Accumulating negatively avoids surprises near MAX_VALUE
439 digit = Character.digit(s.charAt(i++),radix);
441 throw NumberFormatException.forInputString(s);
443 if (result < multmin) {
444 throw NumberFormatException.forInputString(s);
447 if (result < limit + digit) {
448 throw NumberFormatException.forInputString(s);
453 throw NumberFormatException.forInputString(s);
455 return negative ? result : -result;
459 * Parses the string argument as a signed decimal {@code long}.
460 * The characters in the string must all be decimal digits, except
461 * that the first character may be an ASCII minus sign {@code '-'}
462 * (<code>\u002D'</code>) to indicate a negative value or an
463 * ASCII plus sign {@code '+'} (<code>'\u002B'</code>) to
464 * indicate a positive value. The resulting {@code long} value is
465 * returned, exactly as if the argument and the radix {@code 10}
466 * were given as arguments to the {@link
467 * #parseLong(java.lang.String, int)} method.
469 * <p>Note that neither the character {@code L}
470 * (<code>'\u004C'</code>) nor {@code l}
471 * (<code>'\u006C'</code>) is permitted to appear at the end
472 * of the string as a type indicator, as would be permitted in
473 * Java programming language source code.
475 * @param s a {@code String} containing the {@code long}
476 * representation to be parsed
477 * @return the {@code long} represented by the argument in
479 * @throws NumberFormatException if the string does not contain a
480 * parsable {@code long}.
482 public static long parseLong(String s) throws NumberFormatException {
483 return parseLong(s, 10);
487 * Returns a {@code Long} object holding the value
488 * extracted from the specified {@code String} when parsed
489 * with the radix given by the second argument. The first
490 * argument is interpreted as representing a signed
491 * {@code long} in the radix specified by the second
492 * argument, exactly as if the arguments were given to the {@link
493 * #parseLong(java.lang.String, int)} method. The result is a
494 * {@code Long} object that represents the {@code long}
495 * value specified by the string.
497 * <p>In other words, this method returns a {@code Long} object equal
501 * {@code new Long(Long.parseLong(s, radix))}
504 * @param s the string to be parsed
505 * @param radix the radix to be used in interpreting {@code s}
506 * @return a {@code Long} object holding the value
507 * represented by the string argument in the specified
509 * @throws NumberFormatException If the {@code String} does not
510 * contain a parsable {@code long}.
512 public static Long valueOf(String s, int radix) throws NumberFormatException {
513 return Long.valueOf(parseLong(s, radix));
517 * Returns a {@code Long} object holding the value
518 * of the specified {@code String}. The argument is
519 * interpreted as representing a signed decimal {@code long},
520 * exactly as if the argument were given to the {@link
521 * #parseLong(java.lang.String)} method. The result is a
522 * {@code Long} object that represents the integer value
523 * specified by the string.
525 * <p>In other words, this method returns a {@code Long} object
526 * equal to the value of:
529 * {@code new Long(Long.parseLong(s))}
532 * @param s the string to be parsed.
533 * @return a {@code Long} object holding the value
534 * represented by the string argument.
535 * @throws NumberFormatException If the string cannot be parsed
538 public static Long valueOf(String s) throws NumberFormatException
540 return Long.valueOf(parseLong(s, 10));
543 private static class LongCache {
544 private LongCache(){}
546 static final Long cache[] = new Long[-(-128) + 127 + 1];
549 for(int i = 0; i < cache.length; i++)
550 cache[i] = new Long(i - 128);
555 * Returns a {@code Long} instance representing the specified
556 * {@code long} value.
557 * If a new {@code Long} instance is not required, this method
558 * should generally be used in preference to the constructor
559 * {@link #Long(long)}, as this method is likely to yield
560 * significantly better space and time performance by caching
561 * frequently requested values.
563 * Note that unlike the {@linkplain Integer#valueOf(int)
564 * corresponding method} in the {@code Integer} class, this method
565 * is <em>not</em> required to cache values within a particular
568 * @param l a long value.
569 * @return a {@code Long} instance representing {@code l}.
572 public static Long valueOf(long l) {
573 final int offset = 128;
574 if (l >= -128 && l <= 127) { // will cache
575 return LongCache.cache[(int)l + offset];
581 * Decodes a {@code String} into a {@code Long}.
582 * Accepts decimal, hexadecimal, and octal numbers given by the
587 * <dt><i>DecodableString:</i>
588 * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
589 * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
590 * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
591 * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
592 * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
600 * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
601 * are as defined in section 3.10.1 of
602 * <cite>The Java™ Language Specification</cite>,
603 * except that underscores are not accepted between digits.
605 * <p>The sequence of characters following an optional
606 * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
607 * "{@code #}", or leading zero) is parsed as by the {@code
608 * Long.parseLong} method with the indicated radix (10, 16, or 8).
609 * This sequence of characters must represent a positive value or
610 * a {@link NumberFormatException} will be thrown. The result is
611 * negated if first character of the specified {@code String} is
612 * the minus sign. No whitespace characters are permitted in the
615 * @param nm the {@code String} to decode.
616 * @return a {@code Long} object holding the {@code long}
617 * value represented by {@code nm}
618 * @throws NumberFormatException if the {@code String} does not
619 * contain a parsable {@code long}.
620 * @see java.lang.Long#parseLong(String, int)
623 public static Long decode(String nm) throws NumberFormatException {
626 boolean negative = false;
629 if (nm.length() == 0)
630 throw new NumberFormatException("Zero length string");
631 char firstChar = nm.charAt(0);
632 // Handle sign, if present
633 if (firstChar == '-') {
636 } else if (firstChar == '+')
639 // Handle radix specifier, if present
640 if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
644 else if (nm.startsWith("#", index)) {
648 else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
653 if (nm.startsWith("-", index) || nm.startsWith("+", index))
654 throw new NumberFormatException("Sign character in wrong position");
657 result = Long.valueOf(nm.substring(index), radix);
658 result = negative ? Long.valueOf(-result.longValue()) : result;
659 } catch (NumberFormatException e) {
660 // If number is Long.MIN_VALUE, we'll end up here. The next line
661 // handles this case, and causes any genuine format error to be
663 String constant = negative ? ("-" + nm.substring(index))
664 : nm.substring(index);
665 result = Long.valueOf(constant, radix);
671 * The value of the {@code Long}.
675 private final long value;
678 * Constructs a newly allocated {@code Long} object that
679 * represents the specified {@code long} argument.
681 * @param value the value to be represented by the
682 * {@code Long} object.
684 public Long(long value) {
689 * Constructs a newly allocated {@code Long} object that
690 * represents the {@code long} value indicated by the
691 * {@code String} parameter. The string is converted to a
692 * {@code long} value in exactly the manner used by the
693 * {@code parseLong} method for radix 10.
695 * @param s the {@code String} to be converted to a
697 * @throws NumberFormatException if the {@code String} does not
698 * contain a parsable {@code long}.
699 * @see java.lang.Long#parseLong(java.lang.String, int)
701 public Long(String s) throws NumberFormatException {
702 this.value = parseLong(s, 10);
706 * Returns the value of this {@code Long} as a
709 public byte byteValue() {
714 * Returns the value of this {@code Long} as a
717 public short shortValue() {
722 * Returns the value of this {@code Long} as an
725 public int intValue() {
730 * Returns the value of this {@code Long} as a
731 * {@code long} value.
733 public long longValue() {
738 * Returns the value of this {@code Long} as a
741 public float floatValue() {
746 * Returns the value of this {@code Long} as a
749 public double doubleValue() {
750 return (double)value;
754 * Returns a {@code String} object representing this
755 * {@code Long}'s value. The value is converted to signed
756 * decimal representation and returned as a string, exactly as if
757 * the {@code long} value were given as an argument to the
758 * {@link java.lang.Long#toString(long)} method.
760 * @return a string representation of the value of this object in
763 public String toString() {
764 return toString(value);
768 * Returns a hash code for this {@code Long}. The result is
769 * the exclusive OR of the two halves of the primitive
770 * {@code long} value held by this {@code Long}
771 * object. That is, the hashcode is the value of the expression:
774 * {@code (int)(this.longValue()^(this.longValue()>>>32))}
777 * @return a hash code value for this object.
779 public int hashCode() {
780 return (int)(value ^ (value >>> 32));
784 * Compares this object to the specified object. The result is
785 * {@code true} if and only if the argument is not
786 * {@code null} and is a {@code Long} object that
787 * contains the same {@code long} value as this object.
789 * @param obj the object to compare with.
790 * @return {@code true} if the objects are the same;
791 * {@code false} otherwise.
793 public boolean equals(Object obj) {
794 if (obj instanceof Long) {
795 return value == ((Long)obj).longValue();
801 * Determines the {@code long} value of the system property
802 * with the specified name.
804 * <p>The first argument is treated as the name of a system property.
805 * System properties are accessible through the {@link
806 * java.lang.System#getProperty(java.lang.String)} method. The
807 * string value of this property is then interpreted as a
808 * {@code long} value and a {@code Long} object
809 * representing this value is returned. Details of possible
810 * numeric formats can be found with the definition of
811 * {@code getProperty}.
813 * <p>If there is no property with the specified name, if the
814 * specified name is empty or {@code null}, or if the
815 * property does not have the correct numeric format, then
816 * {@code null} is returned.
818 * <p>In other words, this method returns a {@code Long} object equal to
822 * {@code getLong(nm, null)}
825 * @param nm property name.
826 * @return the {@code Long} value of the property.
827 * @see java.lang.System#getProperty(java.lang.String)
828 * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
830 public static Long getLong(String nm) {
831 return getLong(nm, null);
835 * Determines the {@code long} value of the system property
836 * with the specified name.
838 * <p>The first argument is treated as the name of a system property.
839 * System properties are accessible through the {@link
840 * java.lang.System#getProperty(java.lang.String)} method. The
841 * string value of this property is then interpreted as a
842 * {@code long} value and a {@code Long} object
843 * representing this value is returned. Details of possible
844 * numeric formats can be found with the definition of
845 * {@code getProperty}.
847 * <p>The second argument is the default value. A {@code Long} object
848 * that represents the value of the second argument is returned if there
849 * is no property of the specified name, if the property does not have
850 * the correct numeric format, or if the specified name is empty or null.
852 * <p>In other words, this method returns a {@code Long} object equal
856 * {@code getLong(nm, new Long(val))}
859 * but in practice it may be implemented in a manner such as:
862 * Long result = getLong(nm, null);
863 * return (result == null) ? new Long(val) : result;
864 * </pre></blockquote>
866 * to avoid the unnecessary allocation of a {@code Long} object when
867 * the default value is not needed.
869 * @param nm property name.
870 * @param val default value.
871 * @return the {@code Long} value of the property.
872 * @see java.lang.System#getProperty(java.lang.String)
873 * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
875 public static Long getLong(String nm, long val) {
876 Long result = Long.getLong(nm, null);
877 return (result == null) ? Long.valueOf(val) : result;
881 * Returns the {@code long} value of the system property with
882 * the specified name. The first argument is treated as the name
883 * of a system property. System properties are accessible through
884 * the {@link java.lang.System#getProperty(java.lang.String)}
885 * method. The string value of this property is then interpreted
886 * as a {@code long} value, as per the
887 * {@code Long.decode} method, and a {@code Long} object
888 * representing this value is returned.
891 * <li>If the property value begins with the two ASCII characters
892 * {@code 0x} or the ASCII character {@code #}, not followed by
893 * a minus sign, then the rest of it is parsed as a hexadecimal integer
894 * exactly as for the method {@link #valueOf(java.lang.String, int)}
896 * <li>If the property value begins with the ASCII character
897 * {@code 0} followed by another character, it is parsed as
898 * an octal integer exactly as by the method {@link
899 * #valueOf(java.lang.String, int)} with radix 8.
900 * <li>Otherwise the property value is parsed as a decimal
901 * integer exactly as by the method
902 * {@link #valueOf(java.lang.String, int)} with radix 10.
905 * <p>Note that, in every case, neither {@code L}
906 * (<code>'\u004C'</code>) nor {@code l}
907 * (<code>'\u006C'</code>) is permitted to appear at the end
908 * of the property value as a type indicator, as would be
909 * permitted in Java programming language source code.
911 * <p>The second argument is the default value. The default value is
912 * returned if there is no property of the specified name, if the
913 * property does not have the correct numeric format, or if the
914 * specified name is empty or {@code null}.
916 * @param nm property name.
917 * @param val default value.
918 * @return the {@code Long} value of the property.
919 * @see java.lang.System#getProperty(java.lang.String)
920 * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
921 * @see java.lang.Long#decode
923 public static Long getLong(String nm, Long val) {
926 v = String.getProperty(nm);
927 } catch (IllegalArgumentException e) {
928 } catch (NullPointerException e) {
932 return Long.decode(v);
933 } catch (NumberFormatException e) {
940 * Compares two {@code Long} objects numerically.
942 * @param anotherLong the {@code Long} to be compared.
943 * @return the value {@code 0} if this {@code Long} is
944 * equal to the argument {@code Long}; a value less than
945 * {@code 0} if this {@code Long} is numerically less
946 * than the argument {@code Long}; and a value greater
947 * than {@code 0} if this {@code Long} is numerically
948 * greater than the argument {@code Long} (signed
952 public int compareTo(Long anotherLong) {
953 return compare(this.value, anotherLong.value);
957 * Compares two {@code long} values numerically.
958 * The value returned is identical to what would be returned by:
960 * Long.valueOf(x).compareTo(Long.valueOf(y))
963 * @param x the first {@code long} to compare
964 * @param y the second {@code long} to compare
965 * @return the value {@code 0} if {@code x == y};
966 * a value less than {@code 0} if {@code x < y}; and
967 * a value greater than {@code 0} if {@code x > y}
970 public static int compare(long x, long y) {
971 return (x < y) ? -1 : ((x == y) ? 0 : 1);
978 * The number of bits used to represent a {@code long} value in two's
979 * complement binary form.
983 public static final int SIZE = 64;
986 * Returns a {@code long} value with at most a single one-bit, in the
987 * position of the highest-order ("leftmost") one-bit in the specified
988 * {@code long} value. Returns zero if the specified value has no
989 * one-bits in its two's complement binary representation, that is, if it
992 * @return a {@code long} value with a single one-bit, in the position
993 * of the highest-order one-bit in the specified value, or zero if
994 * the specified value is itself equal to zero.
997 public static long highestOneBit(long i) {
1005 return i - (i >>> 1);
1009 * Returns a {@code long} value with at most a single one-bit, in the
1010 * position of the lowest-order ("rightmost") one-bit in the specified
1011 * {@code long} value. Returns zero if the specified value has no
1012 * one-bits in its two's complement binary representation, that is, if it
1015 * @return a {@code long} value with a single one-bit, in the position
1016 * of the lowest-order one-bit in the specified value, or zero if
1017 * the specified value is itself equal to zero.
1020 public static long lowestOneBit(long i) {
1026 * Returns the number of zero bits preceding the highest-order
1027 * ("leftmost") one-bit in the two's complement binary representation
1028 * of the specified {@code long} value. Returns 64 if the
1029 * specified value has no one-bits in its two's complement representation,
1030 * in other words if it is equal to zero.
1032 * <p>Note that this method is closely related to the logarithm base 2.
1033 * For all positive {@code long} values x:
1035 * <li>floor(log<sub>2</sub>(x)) = {@code 63 - numberOfLeadingZeros(x)}
1036 * <li>ceil(log<sub>2</sub>(x)) = {@code 64 - numberOfLeadingZeros(x - 1)}
1039 * @return the number of zero bits preceding the highest-order
1040 * ("leftmost") one-bit in the two's complement binary representation
1041 * of the specified {@code long} value, or 64 if the value
1045 public static int numberOfLeadingZeros(long i) {
1050 int x = (int)(i >>> 32);
1051 if (x == 0) { n += 32; x = (int)i; }
1052 if (x >>> 16 == 0) { n += 16; x <<= 16; }
1053 if (x >>> 24 == 0) { n += 8; x <<= 8; }
1054 if (x >>> 28 == 0) { n += 4; x <<= 4; }
1055 if (x >>> 30 == 0) { n += 2; x <<= 2; }
1061 * Returns the number of zero bits following the lowest-order ("rightmost")
1062 * one-bit in the two's complement binary representation of the specified
1063 * {@code long} value. Returns 64 if the specified value has no
1064 * one-bits in its two's complement representation, in other words if it is
1067 * @return the number of zero bits following the lowest-order ("rightmost")
1068 * one-bit in the two's complement binary representation of the
1069 * specified {@code long} value, or 64 if the value is equal
1073 public static int numberOfTrailingZeros(long i) {
1076 if (i == 0) return 64;
1078 y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32);
1079 y = x <<16; if (y != 0) { n = n -16; x = y; }
1080 y = x << 8; if (y != 0) { n = n - 8; x = y; }
1081 y = x << 4; if (y != 0) { n = n - 4; x = y; }
1082 y = x << 2; if (y != 0) { n = n - 2; x = y; }
1083 return n - ((x << 1) >>> 31);
1087 * Returns the number of one-bits in the two's complement binary
1088 * representation of the specified {@code long} value. This function is
1089 * sometimes referred to as the <i>population count</i>.
1091 * @return the number of one-bits in the two's complement binary
1092 * representation of the specified {@code long} value.
1095 public static int bitCount(long i) {
1097 i = i - ((i >>> 1) & 0x5555555555555555L);
1098 i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L);
1099 i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL;
1103 return (int)i & 0x7f;
1107 * Returns the value obtained by rotating the two's complement binary
1108 * representation of the specified {@code long} value left by the
1109 * specified number of bits. (Bits shifted out of the left hand, or
1110 * high-order, side reenter on the right, or low-order.)
1112 * <p>Note that left rotation with a negative distance is equivalent to
1113 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
1114 * distance)}. Note also that rotation by any multiple of 64 is a
1115 * no-op, so all but the last six bits of the rotation distance can be
1116 * ignored, even if the distance is negative: {@code rotateLeft(val,
1117 * distance) == rotateLeft(val, distance & 0x3F)}.
1119 * @return the value obtained by rotating the two's complement binary
1120 * representation of the specified {@code long} value left by the
1121 * specified number of bits.
1124 public static long rotateLeft(long i, int distance) {
1125 return (i << distance) | (i >>> -distance);
1129 * Returns the value obtained by rotating the two's complement binary
1130 * representation of the specified {@code long} value right by the
1131 * specified number of bits. (Bits shifted out of the right hand, or
1132 * low-order, side reenter on the left, or high-order.)
1134 * <p>Note that right rotation with a negative distance is equivalent to
1135 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
1136 * distance)}. Note also that rotation by any multiple of 64 is a
1137 * no-op, so all but the last six bits of the rotation distance can be
1138 * ignored, even if the distance is negative: {@code rotateRight(val,
1139 * distance) == rotateRight(val, distance & 0x3F)}.
1141 * @return the value obtained by rotating the two's complement binary
1142 * representation of the specified {@code long} value right by the
1143 * specified number of bits.
1146 public static long rotateRight(long i, int distance) {
1147 return (i >>> distance) | (i << -distance);
1151 * Returns the value obtained by reversing the order of the bits in the
1152 * two's complement binary representation of the specified {@code long}
1155 * @return the value obtained by reversing order of the bits in the
1156 * specified {@code long} value.
1159 public static long reverse(long i) {
1161 i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L;
1162 i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L;
1163 i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL;
1164 i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
1165 i = (i << 48) | ((i & 0xffff0000L) << 16) |
1166 ((i >>> 16) & 0xffff0000L) | (i >>> 48);
1171 * Returns the signum function of the specified {@code long} value. (The
1172 * return value is -1 if the specified value is negative; 0 if the
1173 * specified value is zero; and 1 if the specified value is positive.)
1175 * @return the signum function of the specified {@code long} value.
1178 public static int signum(long i) {
1180 return (int) ((i >> 63) | (-i >>> 63));
1184 * Returns the value obtained by reversing the order of the bytes in the
1185 * two's complement representation of the specified {@code long} value.
1187 * @return the value obtained by reversing the bytes in the specified
1188 * {@code long} value.
1191 public static long reverseBytes(long i) {
1192 i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
1193 return (i << 48) | ((i & 0xffff0000L) << 16) |
1194 ((i >>> 16) & 0xffff0000L) | (i >>> 48);
1197 /** use serialVersionUID from JDK 1.0.2 for interoperability */
1198 private static final long serialVersionUID = 4290774380558885855L;