0001 /*
0002 * Copyright 1994-2006 Sun Microsystems, Inc. All Rights Reserved.
0003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0004 *
0005 * This code is free software; you can redistribute it and/or modify it
0006 * under the terms of the GNU General Public License version 2 only, as
0007 * published by the Free Software Foundation. Sun designates this
0008 * particular file as subject to the "Classpath" exception as provided
0009 * by Sun in the LICENSE file that accompanied this code.
0010 *
0011 * This code is distributed in the hope that it will be useful, but WITHOUT
0012 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0013 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0014 * version 2 for more details (a copy is included in the LICENSE file that
0015 * accompanied this code).
0016 *
0017 * You should have received a copy of the GNU General Public License version
0018 * 2 along with this work; if not, write to the Free Software Foundation,
0019 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0020 *
0021 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
0022 * CA 95054 USA or visit www.sun.com if you need additional information or
0023 * have any questions.
0024 */
0025
0026 package java.lang;
0027
0028 /**
0029 * The {@code Long} class wraps a value of the primitive type {@code
0030 * long} in an object. An object of type {@code Long} contains a
0031 * single field whose type is {@code long}.
0032 *
0033 * <p> In addition, this class provides several methods for converting
0034 * a {@code long} to a {@code String} and a {@code String} to a {@code
0035 * long}, as well as other constants and methods useful when dealing
0036 * with a {@code long}.
0037 *
0038 * <p>Implementation note: The implementations of the "bit twiddling"
0039 * methods (such as {@link #highestOneBit(long) highestOneBit} and
0040 * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are
0041 * based on material from Henry S. Warren, Jr.'s <i>Hacker's
0042 * Delight</i>, (Addison Wesley, 2002).
0043 *
0044 * @author Lee Boynton
0045 * @author Arthur van Hoff
0046 * @author Josh Bloch
0047 * @author Joseph D. Darcy
0048 * @version 1.91, 07/12/07
0049 * @since JDK1.0
0050 */
0051 public final class Long extends Number implements Comparable<Long> {
0052 /**
0053 * A constant holding the minimum value a {@code long} can
0054 * have, -2<sup>63</sup>.
0055 */
0056 public static final long MIN_VALUE = 0x8000000000000000L;
0057
0058 /**
0059 * A constant holding the maximum value a {@code long} can
0060 * have, 2<sup>63</sup>-1.
0061 */
0062 public static final long MAX_VALUE = 0x7fffffffffffffffL;
0063
0064 /**
0065 * The {@code Class} instance representing the primitive type
0066 * {@code long}.
0067 *
0068 * @since JDK1.1
0069 */
0070 public static final Class<Long> TYPE = (Class<Long>) Class
0071 .getPrimitiveClass("long");
0072
0073 /**
0074 * Returns a string representation of the first argument in the
0075 * radix specified by the second argument.
0076 *
0077 * <p>If the radix is smaller than {@code Character.MIN_RADIX}
0078 * or larger than {@code Character.MAX_RADIX}, then the radix
0079 * {@code 10} is used instead.
0080 *
0081 * <p>If the first argument is negative, the first element of the
0082 * result is the ASCII minus sign {@code '-'}
0083 * (<code>'\u002d'</code>). If the first argument is not
0084 * negative, no sign character appears in the result.
0085 *
0086 * <p>The remaining characters of the result represent the magnitude
0087 * of the first argument. If the magnitude is zero, it is
0088 * represented by a single zero character {@code '0'}
0089 * (<code>'\u0030'</code>); otherwise, the first character of
0090 * the representation of the magnitude will not be the zero
0091 * character. The following ASCII characters are used as digits:
0092 *
0093 * <blockquote>
0094 * {@code 0123456789abcdefghijklmnopqrstuvwxyz}
0095 * </blockquote>
0096 *
0097 * These are <code>'\u0030'</code> through
0098 * <code>'\u0039'</code> and <code>'\u0061'</code> through
0099 * <code>'\u007a'</code>. If {@code radix} is
0100 * <var>N</var>, then the first <var>N</var> of these characters
0101 * are used as radix-<var>N</var> digits in the order shown. Thus,
0102 * the digits for hexadecimal (radix 16) are
0103 * {@code 0123456789abcdef}. If uppercase letters are
0104 * desired, the {@link java.lang.String#toUpperCase()} method may
0105 * be called on the result:
0106 *
0107 * <blockquote>
0108 * {@code Long.toString(n, 16).toUpperCase()}
0109 * </blockquote>
0110 *
0111 * @param i a {@code long} to be converted to a string.
0112 * @param radix the radix to use in the string representation.
0113 * @return a string representation of the argument in the specified radix.
0114 * @see java.lang.Character#MAX_RADIX
0115 * @see java.lang.Character#MIN_RADIX
0116 */
0117 public static String toString(long i, int radix) {
0118 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
0119 radix = 10;
0120 if (radix == 10)
0121 return toString(i);
0122 char[] buf = new char[65];
0123 int charPos = 64;
0124 boolean negative = (i < 0);
0125
0126 if (!negative) {
0127 i = -i;
0128 }
0129
0130 while (i <= -radix) {
0131 buf[charPos--] = Integer.digits[(int) (-(i % radix))];
0132 i = i / radix;
0133 }
0134 buf[charPos] = Integer.digits[(int) (-i)];
0135
0136 if (negative) {
0137 buf[--charPos] = '-';
0138 }
0139
0140 return new String(buf, charPos, (65 - charPos));
0141 }
0142
0143 /**
0144 * Returns a string representation of the {@code long}
0145 * argument as an unsigned integer in base 16.
0146 *
0147 * <p>The unsigned {@code long} value is the argument plus
0148 * 2<sup>64</sup> if the argument is negative; otherwise, it is
0149 * equal to the argument. This value is converted to a string of
0150 * ASCII digits in hexadecimal (base 16) with no extra
0151 * leading {@code 0}s. If the unsigned magnitude is zero, it
0152 * is represented by a single zero character {@code '0'}
0153 * (<code>'\u0030'</code>); otherwise, the first character of
0154 * the representation of the unsigned magnitude will not be the
0155 * zero character. The following characters are used as
0156 * hexadecimal digits:
0157 *
0158 * <blockquote>
0159 * {@code 0123456789abcdef}
0160 * </blockquote>
0161 *
0162 * These are the characters <code>'\u0030'</code> through
0163 * <code>'\u0039'</code> and <code>'\u0061'</code> through
0164 * <code>'\u0066'</code>. If uppercase letters are desired,
0165 * the {@link java.lang.String#toUpperCase()} method may be called
0166 * on the result:
0167 *
0168 * <blockquote>
0169 * {@code Long.toHexString(n).toUpperCase()}
0170 * </blockquote>
0171 *
0172 * @param i a {@code long} to be converted to a string.
0173 * @return the string representation of the unsigned {@code long}
0174 * value represented by the argument in hexadecimal
0175 * (base 16).
0176 * @since JDK 1.0.2
0177 */
0178 public static String toHexString(long i) {
0179 return toUnsignedString(i, 4);
0180 }
0181
0182 /**
0183 * Returns a string representation of the {@code long}
0184 * argument as an unsigned integer in base 8.
0185 *
0186 * <p>The unsigned {@code long} value is the argument plus
0187 * 2<sup>64</sup> if the argument is negative; otherwise, it is
0188 * equal to the argument. This value is converted to a string of
0189 * ASCII digits in octal (base 8) with no extra leading
0190 * {@code 0}s.
0191 *
0192 * <p>If the unsigned magnitude is zero, it is represented by a
0193 * single zero character {@code '0'}
0194 * (<code>'\u0030'</code>); otherwise, the first character of
0195 * the representation of the unsigned magnitude will not be the
0196 * zero character. The following characters are used as octal
0197 * digits:
0198 *
0199 * <blockquote>
0200 * {@code 01234567}
0201 * </blockquote>
0202 *
0203 * These are the characters <code>'\u0030'</code> through
0204 * <code>'\u0037'</code>.
0205 *
0206 * @param i a {@code long} to be converted to a string.
0207 * @return the string representation of the unsigned {@code long}
0208 * value represented by the argument in octal (base 8).
0209 * @since JDK 1.0.2
0210 */
0211 public static String toOctalString(long i) {
0212 return toUnsignedString(i, 3);
0213 }
0214
0215 /**
0216 * Returns a string representation of the {@code long}
0217 * argument as an unsigned integer in base 2.
0218 *
0219 * <p>The unsigned {@code long} value is the argument plus
0220 * 2<sup>64</sup> if the argument is negative; otherwise, it is
0221 * equal to the argument. This value is converted to a string of
0222 * ASCII digits in binary (base 2) with no extra leading
0223 * {@code 0}s. If the unsigned magnitude is zero, it is
0224 * represented by a single zero character {@code '0'}
0225 * (<code>'\u0030'</code>); otherwise, the first character of
0226 * the representation of the unsigned magnitude will not be the
0227 * zero character. The characters {@code '0'}
0228 * (<code>'\u0030'</code>) and {@code '1'}
0229 * (<code>'\u0031'</code>) are used as binary digits.
0230 *
0231 * @param i a {@code long} to be converted to a string.
0232 * @return the string representation of the unsigned {@code long}
0233 * value represented by the argument in binary (base 2).
0234 * @since JDK 1.0.2
0235 */
0236 public static String toBinaryString(long i) {
0237 return toUnsignedString(i, 1);
0238 }
0239
0240 /**
0241 * Convert the integer to an unsigned number.
0242 */
0243 private static String toUnsignedString(long i, int shift) {
0244 char[] buf = new char[64];
0245 int charPos = 64;
0246 int radix = 1 << shift;
0247 long mask = radix - 1;
0248 do {
0249 buf[--charPos] = Integer.digits[(int) (i & mask)];
0250 i >>>= shift;
0251 } while (i != 0);
0252 return new String(buf, charPos, (64 - charPos));
0253 }
0254
0255 /**
0256 * Returns a {@code String} object representing the specified
0257 * {@code long}. The argument is converted to signed decimal
0258 * representation and returned as a string, exactly as if the
0259 * argument and the radix 10 were given as arguments to the {@link
0260 * #toString(long, int)} method.
0261 *
0262 * @param i a {@code long} to be converted.
0263 * @return a string representation of the argument in base 10.
0264 */
0265 public static String toString(long i) {
0266 if (i == Long.MIN_VALUE)
0267 return "-9223372036854775808";
0268 int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
0269 char[] buf = new char[size];
0270 getChars(i, size, buf);
0271 return new String(0, size, buf);
0272 }
0273
0274 /**
0275 * Places characters representing the integer i into the
0276 * character array buf. The characters are placed into
0277 * the buffer backwards starting with the least significant
0278 * digit at the specified index (exclusive), and working
0279 * backwards from there.
0280 *
0281 * Will fail if i == Long.MIN_VALUE
0282 */
0283 static void getChars(long i, int index, char[] buf) {
0284 long q;
0285 int r;
0286 int charPos = index;
0287 char sign = 0;
0288
0289 if (i < 0) {
0290 sign = '-';
0291 i = -i;
0292 }
0293
0294 // Get 2 digits/iteration using longs until quotient fits into an int
0295 while (i > Integer.MAX_VALUE) {
0296 q = i / 100;
0297 // really: r = i - (q * 100);
0298 r = (int) (i - ((q << 6) + (q << 5) + (q << 2)));
0299 i = q;
0300 buf[--charPos] = Integer.DigitOnes[r];
0301 buf[--charPos] = Integer.DigitTens[r];
0302 }
0303
0304 // Get 2 digits/iteration using ints
0305 int q2;
0306 int i2 = (int) i;
0307 while (i2 >= 65536) {
0308 q2 = i2 / 100;
0309 // really: r = i2 - (q * 100);
0310 r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
0311 i2 = q2;
0312 buf[--charPos] = Integer.DigitOnes[r];
0313 buf[--charPos] = Integer.DigitTens[r];
0314 }
0315
0316 // Fall thru to fast mode for smaller numbers
0317 // assert(i2 <= 65536, i2);
0318 for (;;) {
0319 q2 = (i2 * 52429) >>> (16 + 3);
0320 r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ...
0321 buf[--charPos] = Integer.digits[r];
0322 i2 = q2;
0323 if (i2 == 0)
0324 break;
0325 }
0326 if (sign != 0) {
0327 buf[--charPos] = sign;
0328 }
0329 }
0330
0331 // Requires positive x
0332 static int stringSize(long x) {
0333 long p = 10;
0334 for (int i = 1; i < 19; i++) {
0335 if (x < p)
0336 return i;
0337 p = 10 * p;
0338 }
0339 return 19;
0340 }
0341
0342 /**
0343 * Parses the string argument as a signed {@code long} in the
0344 * radix specified by the second argument. The characters in the
0345 * string must all be digits of the specified radix (as determined
0346 * by whether {@link java.lang.Character#digit(char, int)} returns
0347 * a nonnegative value), except that the first character may be an
0348 * ASCII minus sign {@code '-'} (<code>'\u002D'</code>) to
0349 * indicate a negative value or an ASCII plus sign {@code '+'}
0350 * (<code>'\u002B'</code>) to indicate a positive value. The
0351 * resulting {@code long} value is returned.
0352 *
0353 * <p>Note that neither the character {@code L}
0354 * (<code>'\u004C'</code>) nor {@code l}
0355 * (<code>'\u006C'</code>) is permitted to appear at the end
0356 * of the string as a type indicator, as would be permitted in
0357 * Java programming language source code - except that either
0358 * {@code L} or {@code l} may appear as a digit for a
0359 * radix greater than 22.
0360 *
0361 * <p>An exception of type {@code NumberFormatException} is
0362 * thrown if any of the following situations occurs:
0363 * <ul>
0364 *
0365 * <li>The first argument is {@code null} or is a string of
0366 * length zero.
0367 *
0368 * <li>The {@code radix} is either smaller than {@link
0369 * java.lang.Character#MIN_RADIX} or larger than {@link
0370 * java.lang.Character#MAX_RADIX}.
0371 *
0372 * <li>Any character of the string is not a digit of the specified
0373 * radix, except that the first character may be a minus sign
0374 * {@code '-'} (<code>'\u002d'</code>) or plus sign {@code
0375 * '+'} (<code>'\u002B'</code>) provided that the string is
0376 * longer than length 1.
0377 *
0378 * <li>The value represented by the string is not a value of type
0379 * {@code long}.
0380 * </ul>
0381 *
0382 * <p>Examples:
0383 * <blockquote><pre>
0384 * parseLong("0", 10) returns 0L
0385 * parseLong("473", 10) returns 473L
0386 * parseLong("+42", 10) returns 42L
0387 * parseLong("-0", 10) returns 0L
0388 * parseLong("-FF", 16) returns -255L
0389 * parseLong("1100110", 2) returns 102L
0390 * parseLong("99", 8) throws a NumberFormatException
0391 * parseLong("Hazelnut", 10) throws a NumberFormatException
0392 * parseLong("Hazelnut", 36) returns 1356099454469L
0393 * </pre></blockquote>
0394 *
0395 * @param s the {@code String} containing the
0396 * {@code long} representation to be parsed.
0397 * @param radix the radix to be used while parsing {@code s}.
0398 * @return the {@code long} represented by the string argument in
0399 * the specified radix.
0400 * @throws NumberFormatException if the string does not contain a
0401 * parsable {@code long}.
0402 */
0403 public static long parseLong(String s, int radix)
0404 throws NumberFormatException {
0405 if (s == null) {
0406 throw new NumberFormatException("null");
0407 }
0408
0409 if (radix < Character.MIN_RADIX) {
0410 throw new NumberFormatException("radix " + radix
0411 + " less than Character.MIN_RADIX");
0412 }
0413 if (radix > Character.MAX_RADIX) {
0414 throw new NumberFormatException("radix " + radix
0415 + " greater than Character.MAX_RADIX");
0416 }
0417
0418 long result = 0;
0419 boolean negative = false;
0420 int i = 0, len = s.length();
0421 long limit = -Long.MAX_VALUE;
0422 long multmin;
0423 int digit;
0424
0425 if (len > 0) {
0426 char firstChar = s.charAt(0);
0427 if (firstChar < '0') { // Possible leading "+" or "-"
0428 if (firstChar == '-') {
0429 negative = true;
0430 limit = Long.MIN_VALUE;
0431 } else if (firstChar != '+')
0432 throw NumberFormatException.forInputString(s);
0433
0434 if (len == 1) // Cannot have lone "+" or "-"
0435 throw NumberFormatException.forInputString(s);
0436 i++;
0437 }
0438 multmin = limit / radix;
0439 while (i < len) {
0440 // Accumulating negatively avoids surprises near MAX_VALUE
0441 digit = Character.digit(s.charAt(i++), radix);
0442 if (digit < 0) {
0443 throw NumberFormatException.forInputString(s);
0444 }
0445 if (result < multmin) {
0446 throw NumberFormatException.forInputString(s);
0447 }
0448 result *= radix;
0449 if (result < limit + digit) {
0450 throw NumberFormatException.forInputString(s);
0451 }
0452 result -= digit;
0453 }
0454 } else {
0455 throw NumberFormatException.forInputString(s);
0456 }
0457 return negative ? result : -result;
0458 }
0459
0460 /**
0461 * Parses the string argument as a signed decimal {@code long}.
0462 * The characters in the string must all be decimal digits, except
0463 * that the first character may be an ASCII minus sign {@code '-'}
0464 * (<code>\u002D'</code>) to indicate a negative value or an
0465 * ASCII plus sign {@code '+'} (<code>'\u002B'</code>) to
0466 * indicate a positive value. The resulting {@code long} value is
0467 * returned, exactly as if the argument and the radix {@code 10}
0468 * were given as arguments to the {@link
0469 * #parseLong(java.lang.String, int)} method.
0470 *
0471 * <p>Note that neither the character {@code L}
0472 * (<code>'\u004C'</code>) nor {@code l}
0473 * (<code>'\u006C'</code>) is permitted to appear at the end
0474 * of the string as a type indicator, as would be permitted in
0475 * Java programming language source code.
0476 *
0477 * @param s a {@code String} containing the {@code long}
0478 * representation to be parsed
0479 * @return the {@code long} represented by the argument in
0480 * decimal.
0481 * @throws NumberFormatException if the string does not contain a
0482 * parsable {@code long}.
0483 */
0484 public static long parseLong(String s) throws NumberFormatException {
0485 return parseLong(s, 10);
0486 }
0487
0488 /**
0489 * Returns a {@code Long} object holding the value
0490 * extracted from the specified {@code String} when parsed
0491 * with the radix given by the second argument. The first
0492 * argument is interpreted as representing a signed
0493 * {@code long} in the radix specified by the second
0494 * argument, exactly as if the arguments were given to the {@link
0495 * #parseLong(java.lang.String, int)} method. The result is a
0496 * {@code Long} object that represents the {@code long}
0497 * value specified by the string.
0498 *
0499 * <p>In other words, this method returns a {@code Long} object equal
0500 * to the value of:
0501 *
0502 * <blockquote>
0503 * {@code new Long(Long.parseLong(s, radix))}
0504 * </blockquote>
0505 *
0506 * @param s the string to be parsed
0507 * @param radix the radix to be used in interpreting {@code s}
0508 * @return a {@code Long} object holding the value
0509 * represented by the string argument in the specified
0510 * radix.
0511 * @throws NumberFormatException If the {@code String} does not
0512 * contain a parsable {@code long}.
0513 */
0514 public static Long valueOf(String s, int radix)
0515 throws NumberFormatException {
0516 return new Long(parseLong(s, radix));
0517 }
0518
0519 /**
0520 * Returns a {@code Long} object holding the value
0521 * of the specified {@code String}. The argument is
0522 * interpreted as representing a signed decimal {@code long},
0523 * exactly as if the argument were given to the {@link
0524 * #parseLong(java.lang.String)} method. The result is a
0525 * {@code Long} object that represents the integer value
0526 * specified by the string.
0527 *
0528 * <p>In other words, this method returns a {@code Long} object
0529 * equal to the value of:
0530 *
0531 * <blockquote>
0532 * {@code new Long(Long.parseLong(s))}
0533 * </blockquote>
0534 *
0535 * @param s the string to be parsed.
0536 * @return a {@code Long} object holding the value
0537 * represented by the string argument.
0538 * @throws NumberFormatException If the string cannot be parsed
0539 * as a {@code long}.
0540 */
0541 public static Long valueOf(String s) throws NumberFormatException {
0542 return new Long(parseLong(s, 10));
0543 }
0544
0545 private static class LongCache {
0546 private LongCache() {
0547 }
0548
0549 static final Long cache[] = new Long[-(-128) + 127 + 1];
0550
0551 static {
0552 for (int i = 0; i < cache.length; i++)
0553 cache[i] = new Long(i - 128);
0554 }
0555 }
0556
0557 /**
0558 * Returns a {@code Long} instance representing the specified
0559 * {@code long} value.
0560 * If a new {@code Long} instance is not required, this method
0561 * should generally be used in preference to the constructor
0562 * {@link #Long(long)}, as this method is likely to yield
0563 * significantly better space and time performance by caching
0564 * frequently requested values.
0565 *
0566 * @param l a long value.
0567 * @return a {@code Long} instance representing {@code l}.
0568 * @since 1.5
0569 */
0570 public static Long valueOf(long l) {
0571 final int offset = 128;
0572 if (l >= -128 && l <= 127) { // will cache
0573 return LongCache.cache[(int) l + offset];
0574 }
0575 return new Long(l);
0576 }
0577
0578 /**
0579 * Decodes a {@code String} into a {@code Long}.
0580 * Accepts decimal, hexadecimal, and octal numbers given by the
0581 * following grammar:
0582 *
0583 * <blockquote>
0584 * <dl>
0585 * <dt><i>DecodableString:</i>
0586 * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
0587 * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
0588 * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
0589 * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
0590 * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
0591 * <p>
0592 * <dt><i>Sign:</i>
0593 * <dd>{@code -}
0594 * <dd>{@code +}
0595 * </dl>
0596 * </blockquote>
0597 *
0598 * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
0599 * are defined in <a href="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#48282">§3.10.1</a>
0600 * of the <a href="http://java.sun.com/docs/books/jls/html/">Java
0601 * Language Specification</a>.
0602 *
0603 * <p>The sequence of characters following an optional
0604 * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
0605 * "{@code #}", or leading zero) is parsed as by the {@code
0606 * Long.parseLong} method with the indicated radix (10, 16, or 8).
0607 * This sequence of characters must represent a positive value or
0608 * a {@link NumberFormatException} will be thrown. The result is
0609 * negated if first character of the specified {@code String} is
0610 * the minus sign. No whitespace characters are permitted in the
0611 * {@code String}.
0612 *
0613 * @param nm the {@code String} to decode.
0614 * @return a {@code Long} object holding the {@code long}
0615 * value represented by {@code nm}
0616 * @throws NumberFormatException if the {@code String} does not
0617 * contain a parsable {@code long}.
0618 * @see java.lang.Long#parseLong(String, int)
0619 * @since 1.2
0620 */
0621 public static Long decode(String nm) throws NumberFormatException {
0622 int radix = 10;
0623 int index = 0;
0624 boolean negative = false;
0625 Long result;
0626
0627 if (nm.length() == 0)
0628 throw new NumberFormatException("Zero length string");
0629 char firstChar = nm.charAt(0);
0630 // Handle sign, if present
0631 if (firstChar == '-') {
0632 negative = true;
0633 index++;
0634 } else if (firstChar == '+')
0635 index++;
0636
0637 // Handle radix specifier, if present
0638 if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
0639 index += 2;
0640 radix = 16;
0641 } else if (nm.startsWith("#", index)) {
0642 index++;
0643 radix = 16;
0644 } else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
0645 index++;
0646 radix = 8;
0647 }
0648
0649 if (nm.startsWith("-", index) || nm.startsWith("+", index))
0650 throw new NumberFormatException(
0651 "Sign character in wrong position");
0652
0653 try {
0654 result = Long.valueOf(nm.substring(index), radix);
0655 result = negative ? new Long((long) -result.longValue())
0656 : result;
0657 } catch (NumberFormatException e) {
0658 // If number is Long.MIN_VALUE, we'll end up here. The next line
0659 // handles this case, and causes any genuine format error to be
0660 // rethrown.
0661 String constant = negative ? ("-" + nm.substring(index))
0662 : nm.substring(index);
0663 result = Long.valueOf(constant, radix);
0664 }
0665 return result;
0666 }
0667
0668 /**
0669 * The value of the {@code Long}.
0670 *
0671 * @serial
0672 */
0673 private final long value;
0674
0675 /**
0676 * Constructs a newly allocated {@code Long} object that
0677 * represents the specified {@code long} argument.
0678 *
0679 * @param value the value to be represented by the
0680 * {@code Long} object.
0681 */
0682 public Long(long value) {
0683 this .value = value;
0684 }
0685
0686 /**
0687 * Constructs a newly allocated {@code Long} object that
0688 * represents the {@code long} value indicated by the
0689 * {@code String} parameter. The string is converted to a
0690 * {@code long} value in exactly the manner used by the
0691 * {@code parseLong} method for radix 10.
0692 *
0693 * @param s the {@code String} to be converted to a
0694 * {@code Long}.
0695 * @throws NumberFormatException if the {@code String} does not
0696 * contain a parsable {@code long}.
0697 * @see java.lang.Long#parseLong(java.lang.String, int)
0698 */
0699 public Long(String s) throws NumberFormatException {
0700 this .value = parseLong(s, 10);
0701 }
0702
0703 /**
0704 * Returns the value of this {@code Long} as a
0705 * {@code byte}.
0706 */
0707 public byte byteValue() {
0708 return (byte) value;
0709 }
0710
0711 /**
0712 * Returns the value of this {@code Long} as a
0713 * {@code short}.
0714 */
0715 public short shortValue() {
0716 return (short) value;
0717 }
0718
0719 /**
0720 * Returns the value of this {@code Long} as an
0721 * {@code int}.
0722 */
0723 public int intValue() {
0724 return (int) value;
0725 }
0726
0727 /**
0728 * Returns the value of this {@code Long} as a
0729 * {@code long} value.
0730 */
0731 public long longValue() {
0732 return (long) value;
0733 }
0734
0735 /**
0736 * Returns the value of this {@code Long} as a
0737 * {@code float}.
0738 */
0739 public float floatValue() {
0740 return (float) value;
0741 }
0742
0743 /**
0744 * Returns the value of this {@code Long} as a
0745 * {@code double}.
0746 */
0747 public double doubleValue() {
0748 return (double) value;
0749 }
0750
0751 /**
0752 * Returns a {@code String} object representing this
0753 * {@code Long}'s value. The value is converted to signed
0754 * decimal representation and returned as a string, exactly as if
0755 * the {@code long} value were given as an argument to the
0756 * {@link java.lang.Long#toString(long)} method.
0757 *
0758 * @return a string representation of the value of this object in
0759 * base 10.
0760 */
0761 public String toString() {
0762 return String.valueOf(value);
0763 }
0764
0765 /**
0766 * Returns a hash code for this {@code Long}. The result is
0767 * the exclusive OR of the two halves of the primitive
0768 * {@code long} value held by this {@code Long}
0769 * object. That is, the hashcode is the value of the expression:
0770 *
0771 * <blockquote>
0772 * {@code (int)(this.longValue()^(this.longValue()>>>32))}
0773 * </blockquote>
0774 *
0775 * @return a hash code value for this object.
0776 */
0777 public int hashCode() {
0778 return (int) (value ^ (value >>> 32));
0779 }
0780
0781 /**
0782 * Compares this object to the specified object. The result is
0783 * {@code true} if and only if the argument is not
0784 * {@code null} and is a {@code Long} object that
0785 * contains the same {@code long} value as this object.
0786 *
0787 * @param obj the object to compare with.
0788 * @return {@code true} if the objects are the same;
0789 * {@code false} otherwise.
0790 */
0791 public boolean equals(Object obj) {
0792 if (obj instanceof Long) {
0793 return value == ((Long) obj).longValue();
0794 }
0795 return false;
0796 }
0797
0798 /**
0799 * Determines the {@code long} value of the system property
0800 * with the specified name.
0801 *
0802 * <p>The first argument is treated as the name of a system property.
0803 * System properties are accessible through the {@link
0804 * java.lang.System#getProperty(java.lang.String)} method. The
0805 * string value of this property is then interpreted as a
0806 * {@code long} value and a {@code Long} object
0807 * representing this value is returned. Details of possible
0808 * numeric formats can be found with the definition of
0809 * {@code getProperty}.
0810 *
0811 * <p>If there is no property with the specified name, if the
0812 * specified name is empty or {@code null}, or if the
0813 * property does not have the correct numeric format, then
0814 * {@code null} is returned.
0815 *
0816 * <p>In other words, this method returns a {@code Long} object equal to
0817 * the value of:
0818 *
0819 * <blockquote>
0820 * {@code getLong(nm, null)}
0821 * </blockquote>
0822 *
0823 * @param nm property name.
0824 * @return the {@code Long} value of the property.
0825 * @see java.lang.System#getProperty(java.lang.String)
0826 * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
0827 */
0828 public static Long getLong(String nm) {
0829 return getLong(nm, null);
0830 }
0831
0832 /**
0833 * Determines the {@code long} value of the system property
0834 * with the specified name.
0835 *
0836 * <p>The first argument is treated as the name of a system property.
0837 * System properties are accessible through the {@link
0838 * java.lang.System#getProperty(java.lang.String)} method. The
0839 * string value of this property is then interpreted as a
0840 * {@code long} value and a {@code Long} object
0841 * representing this value is returned. Details of possible
0842 * numeric formats can be found with the definition of
0843 * {@code getProperty}.
0844 *
0845 * <p>The second argument is the default value. A {@code Long} object
0846 * that represents the value of the second argument is returned if there
0847 * is no property of the specified name, if the property does not have
0848 * the correct numeric format, or if the specified name is empty or null.
0849 *
0850 * <p>In other words, this method returns a {@code Long} object equal
0851 * to the value of:
0852 *
0853 * <blockquote>
0854 * {@code getLong(nm, new Long(val))}
0855 * </blockquote>
0856 *
0857 * but in practice it may be implemented in a manner such as:
0858 *
0859 * <blockquote><pre>
0860 * Long result = getLong(nm, null);
0861 * return (result == null) ? new Long(val) : result;
0862 * </pre></blockquote>
0863 *
0864 * to avoid the unnecessary allocation of a {@code Long} object when
0865 * the default value is not needed.
0866 *
0867 * @param nm property name.
0868 * @param val default value.
0869 * @return the {@code Long} value of the property.
0870 * @see java.lang.System#getProperty(java.lang.String)
0871 * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
0872 */
0873 public static Long getLong(String nm, long val) {
0874 Long result = Long.getLong(nm, null);
0875 return (result == null) ? new Long(val) : result;
0876 }
0877
0878 /**
0879 * Returns the {@code long} value of the system property with
0880 * the specified name. The first argument is treated as the name
0881 * of a system property. System properties are accessible through
0882 * the {@link java.lang.System#getProperty(java.lang.String)}
0883 * method. The string value of this property is then interpreted
0884 * as a {@code long} value, as per the
0885 * {@code Long.decode} method, and a {@code Long} object
0886 * representing this value is returned.
0887 *
0888 * <ul>
0889 * <li>If the property value begins with the two ASCII characters
0890 * {@code 0x} or the ASCII character {@code #}, not followed by
0891 * a minus sign, then the rest of it is parsed as a hexadecimal integer
0892 * exactly as for the method {@link #valueOf(java.lang.String, int)}
0893 * with radix 16.
0894 * <li>If the property value begins with the ASCII character
0895 * {@code 0} followed by another character, it is parsed as
0896 * an octal integer exactly as by the method {@link
0897 * #valueOf(java.lang.String, int)} with radix 8.
0898 * <li>Otherwise the property value is parsed as a decimal
0899 * integer exactly as by the method
0900 * {@link #valueOf(java.lang.String, int)} with radix 10.
0901 * </ul>
0902 *
0903 * <p>Note that, in every case, neither {@code L}
0904 * (<code>'\u004C'</code>) nor {@code l}
0905 * (<code>'\u006C'</code>) is permitted to appear at the end
0906 * of the property value as a type indicator, as would be
0907 * permitted in Java programming language source code.
0908 *
0909 * <p>The second argument is the default value. The default value is
0910 * returned if there is no property of the specified name, if the
0911 * property does not have the correct numeric format, or if the
0912 * specified name is empty or {@code null}.
0913 *
0914 * @param nm property name.
0915 * @param val default value.
0916 * @return the {@code Long} value of the property.
0917 * @see java.lang.System#getProperty(java.lang.String)
0918 * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
0919 * @see java.lang.Long#decode
0920 */
0921 public static Long getLong(String nm, Long val) {
0922 String v = null;
0923 try {
0924 v = System.getProperty(nm);
0925 } catch (IllegalArgumentException e) {
0926 } catch (NullPointerException e) {
0927 }
0928 if (v != null) {
0929 try {
0930 return Long.decode(v);
0931 } catch (NumberFormatException e) {
0932 }
0933 }
0934 return val;
0935 }
0936
0937 /**
0938 * Compares two {@code Long} objects numerically.
0939 *
0940 * @param anotherLong the {@code Long} to be compared.
0941 * @return the value {@code 0} if this {@code Long} is
0942 * equal to the argument {@code Long}; a value less than
0943 * {@code 0} if this {@code Long} is numerically less
0944 * than the argument {@code Long}; and a value greater
0945 * than {@code 0} if this {@code Long} is numerically
0946 * greater than the argument {@code Long} (signed
0947 * comparison).
0948 * @since 1.2
0949 */
0950 public int compareTo(Long anotherLong) {
0951 long this Val = this .value;
0952 long anotherVal = anotherLong.value;
0953 return (this Val < anotherVal ? -1 : (this Val == anotherVal ? 0
0954 : 1));
0955 }
0956
0957 // Bit Twiddling
0958
0959 /**
0960 * The number of bits used to represent a {@code long} value in two's
0961 * complement binary form.
0962 *
0963 * @since 1.5
0964 */
0965 public static final int SIZE = 64;
0966
0967 /**
0968 * Returns a {@code long} value with at most a single one-bit, in the
0969 * position of the highest-order ("leftmost") one-bit in the specified
0970 * {@code long} value. Returns zero if the specified value has no
0971 * one-bits in its two's complement binary representation, that is, if it
0972 * is equal to zero.
0973 *
0974 * @return a {@code long} value with a single one-bit, in the position
0975 * of the highest-order one-bit in the specified value, or zero if
0976 * the specified value is itself equal to zero.
0977 * @since 1.5
0978 */
0979 public static long highestOneBit(long i) {
0980 // HD, Figure 3-1
0981 i |= (i >> 1);
0982 i |= (i >> 2);
0983 i |= (i >> 4);
0984 i |= (i >> 8);
0985 i |= (i >> 16);
0986 i |= (i >> 32);
0987 return i - (i >>> 1);
0988 }
0989
0990 /**
0991 * Returns a {@code long} value with at most a single one-bit, in the
0992 * position of the lowest-order ("rightmost") one-bit in the specified
0993 * {@code long} value. Returns zero if the specified value has no
0994 * one-bits in its two's complement binary representation, that is, if it
0995 * is equal to zero.
0996 *
0997 * @return a {@code long} value with a single one-bit, in the position
0998 * of the lowest-order one-bit in the specified value, or zero if
0999 * the specified value is itself equal to zero.
1000 * @since 1.5
1001 */
1002 public static long lowestOneBit(long i) {
1003 // HD, Section 2-1
1004 return i & -i;
1005 }
1006
1007 /**
1008 * Returns the number of zero bits preceding the highest-order
1009 * ("leftmost") one-bit in the two's complement binary representation
1010 * of the specified {@code long} value. Returns 64 if the
1011 * specified value has no one-bits in its two's complement representation,
1012 * in other words if it is equal to zero.
1013 *
1014 * <p>Note that this method is closely related to the logarithm base 2.
1015 * For all positive {@code long} values x:
1016 * <ul>
1017 * <li>floor(log<sub>2</sub>(x)) = {@code 63 - numberOfLeadingZeros(x)}
1018 * <li>ceil(log<sub>2</sub>(x)) = {@code 64 - numberOfLeadingZeros(x - 1)}
1019 * </ul>
1020 *
1021 * @return the number of zero bits preceding the highest-order
1022 * ("leftmost") one-bit in the two's complement binary representation
1023 * of the specified {@code long} value, or 64 if the value
1024 * is equal to zero.
1025 * @since 1.5
1026 */
1027 public static int numberOfLeadingZeros(long i) {
1028 // HD, Figure 5-6
1029 if (i == 0)
1030 return 64;
1031 int n = 1;
1032 int x = (int) (i >>> 32);
1033 if (x == 0) {
1034 n += 32;
1035 x = (int) i;
1036 }
1037 if (x >>> 16 == 0) {
1038 n += 16;
1039 x <<= 16;
1040 }
1041 if (x >>> 24 == 0) {
1042 n += 8;
1043 x <<= 8;
1044 }
1045 if (x >>> 28 == 0) {
1046 n += 4;
1047 x <<= 4;
1048 }
1049 if (x >>> 30 == 0) {
1050 n += 2;
1051 x <<= 2;
1052 }
1053 n -= x >>> 31;
1054 return n;
1055 }
1056
1057 /**
1058 * Returns the number of zero bits following the lowest-order ("rightmost")
1059 * one-bit in the two's complement binary representation of the specified
1060 * {@code long} value. Returns 64 if the specified value has no
1061 * one-bits in its two's complement representation, in other words if it is
1062 * equal to zero.
1063 *
1064 * @return the number of zero bits following the lowest-order ("rightmost")
1065 * one-bit in the two's complement binary representation of the
1066 * specified {@code long} value, or 64 if the value is equal
1067 * to zero.
1068 * @since 1.5
1069 */
1070 public static int numberOfTrailingZeros(long i) {
1071 // HD, Figure 5-14
1072 int x, y;
1073 if (i == 0)
1074 return 64;
1075 int n = 63;
1076 y = (int) i;
1077 if (y != 0) {
1078 n = n - 32;
1079 x = y;
1080 } else
1081 x = (int) (i >>> 32);
1082 y = x << 16;
1083 if (y != 0) {
1084 n = n - 16;
1085 x = y;
1086 }
1087 y = x << 8;
1088 if (y != 0) {
1089 n = n - 8;
1090 x = y;
1091 }
1092 y = x << 4;
1093 if (y != 0) {
1094 n = n - 4;
1095 x = y;
1096 }
1097 y = x << 2;
1098 if (y != 0) {
1099 n = n - 2;
1100 x = y;
1101 }
1102 return n - ((x << 1) >>> 31);
1103 }
1104
1105 /**
1106 * Returns the number of one-bits in the two's complement binary
1107 * representation of the specified {@code long} value. This function is
1108 * sometimes referred to as the <i>population count</i>.
1109 *
1110 * @return the number of one-bits in the two's complement binary
1111 * representation of the specified {@code long} value.
1112 * @since 1.5
1113 */
1114 public static int bitCount(long i) {
1115 // HD, Figure 5-14
1116 i = i - ((i >>> 1) & 0x5555555555555555L);
1117 i = (i & 0x3333333333333333L)
1118 + ((i >>> 2) & 0x3333333333333333L);
1119 i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL;
1120 i = i + (i >>> 8);
1121 i = i + (i >>> 16);
1122 i = i + (i >>> 32);
1123 return (int) i & 0x7f;
1124 }
1125
1126 /**
1127 * Returns the value obtained by rotating the two's complement binary
1128 * representation of the specified {@code long} value left by the
1129 * specified number of bits. (Bits shifted out of the left hand, or
1130 * high-order, side reenter on the right, or low-order.)
1131 *
1132 * <p>Note that left rotation with a negative distance is equivalent to
1133 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
1134 * distance)}. Note also that rotation by any multiple of 64 is a
1135 * no-op, so all but the last six bits of the rotation distance can be
1136 * ignored, even if the distance is negative: {@code rotateLeft(val,
1137 * distance) == rotateLeft(val, distance & 0x3F)}.
1138 *
1139 * @return the value obtained by rotating the two's complement binary
1140 * representation of the specified {@code long} value left by the
1141 * specified number of bits.
1142 * @since 1.5
1143 */
1144 public static long rotateLeft(long i, int distance) {
1145 return (i << distance) | (i >>> -distance);
1146 }
1147
1148 /**
1149 * Returns the value obtained by rotating the two's complement binary
1150 * representation of the specified {@code long} value right by the
1151 * specified number of bits. (Bits shifted out of the right hand, or
1152 * low-order, side reenter on the left, or high-order.)
1153 *
1154 * <p>Note that right rotation with a negative distance is equivalent to
1155 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
1156 * distance)}. Note also that rotation by any multiple of 64 is a
1157 * no-op, so all but the last six bits of the rotation distance can be
1158 * ignored, even if the distance is negative: {@code rotateRight(val,
1159 * distance) == rotateRight(val, distance & 0x3F)}.
1160 *
1161 * @return the value obtained by rotating the two's complement binary
1162 * representation of the specified {@code long} value right by the
1163 * specified number of bits.
1164 * @since 1.5
1165 */
1166 public static long rotateRight(long i, int distance) {
1167 return (i >>> distance) | (i << -distance);
1168 }
1169
1170 /**
1171 * Returns the value obtained by reversing the order of the bits in the
1172 * two's complement binary representation of the specified {@code long}
1173 * value.
1174 *
1175 * @return the value obtained by reversing order of the bits in the
1176 * specified {@code long} value.
1177 * @since 1.5
1178 */
1179 public static long reverse(long i) {
1180 // HD, Figure 7-1
1181 i = (i & 0x5555555555555555L) << 1 | (i >>> 1)
1182 & 0x5555555555555555L;
1183 i = (i & 0x3333333333333333L) << 2 | (i >>> 2)
1184 & 0x3333333333333333L;
1185 i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4)
1186 & 0x0f0f0f0f0f0f0f0fL;
1187 i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8)
1188 & 0x00ff00ff00ff00ffL;
1189 i = (i << 48) | ((i & 0xffff0000L) << 16)
1190 | ((i >>> 16) & 0xffff0000L) | (i >>> 48);
1191 return i;
1192 }
1193
1194 /**
1195 * Returns the signum function of the specified {@code long} value. (The
1196 * return value is -1 if the specified value is negative; 0 if the
1197 * specified value is zero; and 1 if the specified value is positive.)
1198 *
1199 * @return the signum function of the specified {@code long} value.
1200 * @since 1.5
1201 */
1202 public static int signum(long i) {
1203 // HD, Section 2-7
1204 return (int) ((i >> 63) | (-i >>> 63));
1205 }
1206
1207 /**
1208 * Returns the value obtained by reversing the order of the bytes in the
1209 * two's complement representation of the specified {@code long} value.
1210 *
1211 * @return the value obtained by reversing the bytes in the specified
1212 * {@code long} value.
1213 * @since 1.5
1214 */
1215 public static long reverseBytes(long i) {
1216 i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8)
1217 & 0x00ff00ff00ff00ffL;
1218 return (i << 48) | ((i & 0xffff0000L) << 16)
1219 | ((i >>> 16) & 0xffff0000L) | (i >>> 48);
1220 }
1221
1222 /** use serialVersionUID from JDK 1.0.2 for interoperability */
1223 private static final long serialVersionUID = 4290774380558885855L;
1224 }
|