1. /*
  2. * @(#)Long.java 1.79 04/05/11
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.lang;
  8. /**
  9. * The <code>Long</code> class wraps a value of the primitive type
  10. * <code>long</code> in an object. An object of type <code>Long</code>
  11. * contains a single field whose type is <code>long</code>.
  12. *
  13. * <p>
  14. *
  15. * In addition, this class provides several methods for converting a
  16. * <code>long</code> to a <code>String</code> and a
  17. * <code>String</code> to a <code>long</code>, as well as other
  18. * constants and methods useful when dealing with a <code>long</code>.
  19. *
  20. * <p>Implementation note: The implementations of the "bit twiddling"
  21. * methods (such as {@link #highestOneBit(long) highestOneBit} and
  22. * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are
  23. * based on material from Henry S. Warren, Jr.'s <i>Hacker's
  24. * Delight</i>, (Addison Wesley, 2002).
  25. *
  26. * @author Lee Boynton
  27. * @author Arthur van Hoff
  28. * @author Josh Bloch
  29. * @version 1.79, 05/11/04
  30. * @since JDK1.0
  31. */
  32. public final class Long extends Number implements Comparable<Long> {
  33. /**
  34. * A constant holding the minimum value a <code>long</code> can
  35. * have, -2<sup>63</sup>.
  36. */
  37. public static final long MIN_VALUE = 0x8000000000000000L;
  38. /**
  39. * A constant holding the maximum value a <code>long</code> can
  40. * have, 2<sup>63</sup>-1.
  41. */
  42. public static final long MAX_VALUE = 0x7fffffffffffffffL;
  43. /**
  44. * The <code>Class</code> instance representing the primitive type
  45. * <code>long</code>.
  46. *
  47. * @since JDK1.1
  48. */
  49. public static final Class<Long> TYPE = (Class<Long>) Class.getPrimitiveClass("long");
  50. /**
  51. * Returns a string representation of the first argument in the
  52. * radix specified by the second argument.
  53. * <p>
  54. * If the radix is smaller than <code>Character.MIN_RADIX</code>
  55. * or larger than <code>Character.MAX_RADIX</code>, then the radix
  56. * <code>10</code> is used instead.
  57. * <p>
  58. * If the first argument is negative, the first element of the
  59. * result is the ASCII minus sign <code>'-'</code>
  60. * (<code>'\u002d'</code>). If the first argument is not
  61. * negative, no sign character appears in the result.
  62. * <p>
  63. * The remaining characters of the result represent the magnitude
  64. * of the first argument. If the magnitude is zero, it is
  65. * represented by a single zero character <code>'0'</code>
  66. * (<code>'\u0030'</code>); otherwise, the first character of
  67. * the representation of the magnitude will not be the zero
  68. * character. The following ASCII characters are used as digits:
  69. * <blockquote><pre>
  70. * 0123456789abcdefghijklmnopqrstuvwxyz
  71. * </pre></blockquote>
  72. * These are <code>'\u0030'</code> through
  73. * <code>'\u0039'</code> and <code>'\u0061'</code> through
  74. * <code>'\u007a'</code>. If <code>radix</code> is
  75. * <var>N</var>, then the first <var>N</var> of these characters
  76. * are used as radix-<var>N</var> digits in the order shown. Thus,
  77. * the digits for hexadecimal (radix 16) are
  78. * <code>0123456789abcdef</code>. If uppercase letters are
  79. * desired, the {@link java.lang.String#toUpperCase()} method may
  80. * be called on the result:
  81. * <blockquote><pre>
  82. * Long.toString(n, 16).toUpperCase()
  83. * </pre></blockquote>
  84. *
  85. * @param i a <code>long</code>to be converted to a string.
  86. * @param radix the radix to use in the string representation.
  87. * @return a string representation of the argument in the specified radix.
  88. * @see java.lang.Character#MAX_RADIX
  89. * @see java.lang.Character#MIN_RADIX
  90. */
  91. public static String toString(long i, int radix) {
  92. if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
  93. radix = 10;
  94. if (radix == 10)
  95. return toString(i);
  96. char[] buf = new char[65];
  97. int charPos = 64;
  98. boolean negative = (i < 0);
  99. if (!negative) {
  100. i = -i;
  101. }
  102. while (i <= -radix) {
  103. buf[charPos--] = Integer.digits[(int)(-(i % radix))];
  104. i = i / radix;
  105. }
  106. buf[charPos] = Integer.digits[(int)(-i)];
  107. if (negative) {
  108. buf[--charPos] = '-';
  109. }
  110. return new String(buf, charPos, (65 - charPos));
  111. }
  112. /**
  113. * Returns a string representation of the <code>long</code>
  114. * argument as an unsigned integer in base 16.
  115. * <p>
  116. * The unsigned <code>long</code> value is the argument plus
  117. * 2<sup>64</sup> if the argument is negative; otherwise, it is
  118. * equal to the argument. This value is converted to a string of
  119. * ASCII digits in hexadecimal (base 16) with no extra
  120. * leading <code>0</code>s. If the unsigned magnitude is zero, it
  121. * is represented by a single zero character <code>'0'</code>
  122. * (<code>'\u0030'</code>); otherwise, the first character of
  123. * the representation of the unsigned magnitude will not be the
  124. * zero character. The following characters are used as
  125. * hexadecimal digits:
  126. * <blockquote><pre>
  127. * 0123456789abcdef
  128. * </pre></blockquote>
  129. * These are the characters <code>'\u0030'</code> through
  130. * <code>'\u0039'</code> and <code>'\u0061'</code> through
  131. * <code>'\u0066'</code>. If uppercase letters are desired,
  132. * the {@link java.lang.String#toUpperCase()} method may be called
  133. * on the result:
  134. * <blockquote><pre>
  135. * Long.toHexString(n).toUpperCase()
  136. * </pre></blockquote>
  137. *
  138. * @param i a <code>long</code> to be converted to a string.
  139. * @return the string representation of the unsigned <code>long</code>
  140. * value represented by the argument in hexadecimal
  141. * (base 16).
  142. * @since JDK 1.0.2
  143. */
  144. public static String toHexString(long i) {
  145. return toUnsignedString(i, 4);
  146. }
  147. /**
  148. * Returns a string representation of the <code>long</code>
  149. * argument as an unsigned integer in base 8.
  150. * <p>
  151. * The unsigned <code>long</code> value is the argument plus
  152. * 2<sup>64</sup> if the argument is negative; otherwise, it is
  153. * equal to the argument. This value is converted to a string of
  154. * ASCII digits in octal (base 8) with no extra leading
  155. * <code>0</code>s.
  156. * <p>
  157. * If the unsigned magnitude is zero, it is represented by a
  158. * single zero character <code>'0'</code>
  159. * (<code>'\u0030'</code>); otherwise, the first character of
  160. * the representation of the unsigned magnitude will not be the
  161. * zero character. The following characters are used as octal
  162. * digits:
  163. * <blockquote><pre>
  164. * 01234567
  165. * </pre></blockquote>
  166. * These are the characters <code>'\u0030'</code> through
  167. * <code>'\u0037'</code>.
  168. *
  169. * @param i a <code>long</code> to be converted to a string.
  170. * @return the string representation of the unsigned <code>long</code>
  171. * value represented by the argument in octal (base 8).
  172. * @since JDK 1.0.2
  173. */
  174. public static String toOctalString(long i) {
  175. return toUnsignedString(i, 3);
  176. }
  177. /**
  178. * Returns a string representation of the <code>long</code>
  179. * argument as an unsigned integer in base 2.
  180. * <p>
  181. * The unsigned <code>long</code> value is the argument plus
  182. * 2<sup>64</sup> if the argument is negative; otherwise, it is
  183. * equal to the argument. This value is converted to a string of
  184. * ASCII digits in binary (base 2) with no extra leading
  185. * <code>0</code>s. If the unsigned magnitude is zero, it is
  186. * represented by a single zero character <code>'0'</code>
  187. * (<code>'\u0030'</code>); otherwise, the first character of
  188. * the representation of the unsigned magnitude will not be the
  189. * zero character. The characters <code>'0'</code>
  190. * (<code>'\u0030'</code>) and <code>'1'</code>
  191. * (<code>'\u0031'</code>) are used as binary digits.
  192. *
  193. * @param i a <code>long</code> to be converted to a string.
  194. * @return the string representation of the unsigned <code>long</code>
  195. * value represented by the argument in binary (base 2).
  196. * @since JDK 1.0.2
  197. */
  198. public static String toBinaryString(long i) {
  199. return toUnsignedString(i, 1);
  200. }
  201. /**
  202. * Convert the integer to an unsigned number.
  203. */
  204. private static String toUnsignedString(long i, int shift) {
  205. char[] buf = new char[64];
  206. int charPos = 64;
  207. int radix = 1 << shift;
  208. long mask = radix - 1;
  209. do {
  210. buf[--charPos] = Integer.digits[(int)(i & mask)];
  211. i >>>= shift;
  212. } while (i != 0);
  213. return new String(buf, charPos, (64 - charPos));
  214. }
  215. /**
  216. * Returns a <code>String</code> object representing the specified
  217. * <code>long</code>. The argument is converted to signed decimal
  218. * representation and returned as a string, exactly as if the
  219. * argument and the radix 10 were given as arguments to the {@link
  220. * #toString(long, int)} method.
  221. *
  222. * @param i a <code>long</code> to be converted.
  223. * @return a string representation of the argument in base 10.
  224. */
  225. public static String toString(long i) {
  226. if (i == Long.MIN_VALUE)
  227. return "-9223372036854775808";
  228. int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
  229. char[] buf = new char[size];
  230. getChars(i, size, buf);
  231. return new String(0, size, buf);
  232. }
  233. /**
  234. * Places characters representing the integer i into the
  235. * character array buf. The characters are placed into
  236. * the buffer backwards starting with the least significant
  237. * digit at the specified index (exclusive), and working
  238. * backwards from there.
  239. *
  240. * Will fail if i == Long.MIN_VALUE
  241. */
  242. static void getChars(long i, int index, char[] buf) {
  243. long q;
  244. int r;
  245. int charPos = index;
  246. char sign = 0;
  247. if (i < 0) {
  248. sign = '-';
  249. i = -i;
  250. }
  251. // Get 2 digits/iteration using longs until quotient fits into an int
  252. while (i > Integer.MAX_VALUE) {
  253. q = i / 100;
  254. // really: r = i - (q * 100);
  255. r = (int)(i - ((q << 6) + (q << 5) + (q << 2)));
  256. i = q;
  257. buf[--charPos] = Integer.DigitOnes[r];
  258. buf[--charPos] = Integer.DigitTens[r];
  259. }
  260. // Get 2 digits/iteration using ints
  261. int q2;
  262. int i2 = (int)i;
  263. while (i2 >= 65536) {
  264. q2 = i2 / 100;
  265. // really: r = i2 - (q * 100);
  266. r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
  267. i2 = q2;
  268. buf[--charPos] = Integer.DigitOnes[r];
  269. buf[--charPos] = Integer.DigitTens[r];
  270. }
  271. // Fall thru to fast mode for smaller numbers
  272. // assert(i2 <= 65536, i2);
  273. for (;;) {
  274. q2 = (i2 * 52429) >>> (16+3);
  275. r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ...
  276. buf[--charPos] = Integer.digits[r];
  277. i2 = q2;
  278. if (i2 == 0) break;
  279. }
  280. if (sign != 0) {
  281. buf[--charPos] = sign;
  282. }
  283. }
  284. // Requires positive x
  285. static int stringSize(long x) {
  286. long p = 10;
  287. for (int i=1; i<19; i++) {
  288. if (x < p)
  289. return i;
  290. p = 10*p;
  291. }
  292. return 19;
  293. }
  294. /**
  295. * Parses the string argument as a signed <code>long</code> in the
  296. * radix specified by the second argument. The characters in the
  297. * string must all be digits of the specified radix (as determined
  298. * by whether {@link java.lang.Character#digit(char, int)} returns
  299. * a nonnegative value), except that the first character may be an
  300. * ASCII minus sign <code>'-'</code> (<code>'\u002D'</code>) to
  301. * indicate a negative value. The resulting <code>long</code>
  302. * value is returned.
  303. * <p>
  304. * Note that neither the character <code>L</code>
  305. * (<code>'\u004C'</code>) nor <code>l</code>
  306. * (<code>'\u006C'</code>) is permitted to appear at the end
  307. * of the string as a type indicator, as would be permitted in
  308. * Java programming language source code - except that either
  309. * <code>L</code> or <code>l</code> may appear as a digit for a
  310. * radix greater than 22.
  311. * <p>
  312. * An exception of type <code>NumberFormatException</code> is
  313. * thrown if any of the following situations occurs:
  314. * <ul>
  315. * <li>The first argument is <code>null</code> or is a string of
  316. * length zero.
  317. * <li>The <code>radix</code> is either smaller than {@link
  318. * java.lang.Character#MIN_RADIX} or larger than {@link
  319. * java.lang.Character#MAX_RADIX}.
  320. * <li>Any character of the string is not a digit of the specified
  321. * radix, except that the first character may be a minus sign
  322. * <code>'-'</code> (<code>'\u002d'</code>) provided that the
  323. * string is longer than length 1.
  324. * <li>The value represented by the string is not a value of type
  325. * <code>long</code>.
  326. * </ul><p>
  327. * Examples:
  328. * <blockquote><pre>
  329. * parseLong("0", 10) returns 0L
  330. * parseLong("473", 10) returns 473L
  331. * parseLong("-0", 10) returns 0L
  332. * parseLong("-FF", 16) returns -255L
  333. * parseLong("1100110", 2) returns 102L
  334. * parseLong("99", 8) throws a NumberFormatException
  335. * parseLong("Hazelnut", 10) throws a NumberFormatException
  336. * parseLong("Hazelnut", 36) returns 1356099454469L
  337. * </pre></blockquote>
  338. *
  339. * @param s the <code>String</code> containing the
  340. * <code>long</code> representation to be parsed.
  341. * @param radix the radix to be used while parsing <code>s</code>.
  342. * @return the <code>long</code> represented by the string argument in
  343. * the specified radix.
  344. * @exception NumberFormatException if the string does not contain a
  345. * parsable <code>long</code>.
  346. */
  347. public static long parseLong(String s, int radix)
  348. throws NumberFormatException
  349. {
  350. if (s == null) {
  351. throw new NumberFormatException("null");
  352. }
  353. if (radix < Character.MIN_RADIX) {
  354. throw new NumberFormatException("radix " + radix +
  355. " less than Character.MIN_RADIX");
  356. }
  357. if (radix > Character.MAX_RADIX) {
  358. throw new NumberFormatException("radix " + radix +
  359. " greater than Character.MAX_RADIX");
  360. }
  361. long result = 0;
  362. boolean negative = false;
  363. int i = 0, max = s.length();
  364. long limit;
  365. long multmin;
  366. int digit;
  367. if (max > 0) {
  368. if (s.charAt(0) == '-') {
  369. negative = true;
  370. limit = Long.MIN_VALUE;
  371. i++;
  372. } else {
  373. limit = -Long.MAX_VALUE;
  374. }
  375. multmin = limit / radix;
  376. if (i < max) {
  377. digit = Character.digit(s.charAt(i++),radix);
  378. if (digit < 0) {
  379. throw NumberFormatException.forInputString(s);
  380. } else {
  381. result = -digit;
  382. }
  383. }
  384. while (i < max) {
  385. // Accumulating negatively avoids surprises near MAX_VALUE
  386. digit = Character.digit(s.charAt(i++),radix);
  387. if (digit < 0) {
  388. throw NumberFormatException.forInputString(s);
  389. }
  390. if (result < multmin) {
  391. throw NumberFormatException.forInputString(s);
  392. }
  393. result *= radix;
  394. if (result < limit + digit) {
  395. throw NumberFormatException.forInputString(s);
  396. }
  397. result -= digit;
  398. }
  399. } else {
  400. throw NumberFormatException.forInputString(s);
  401. }
  402. if (negative) {
  403. if (i > 1) {
  404. return result;
  405. } else { /* Only got "-" */
  406. throw NumberFormatException.forInputString(s);
  407. }
  408. } else {
  409. return -result;
  410. }
  411. }
  412. /**
  413. * Parses the string argument as a signed decimal
  414. * <code>long</code>. The characters in the string must all be
  415. * decimal digits, except that the first character may be an ASCII
  416. * minus sign <code>'-'</code> (<code>\u002D'</code>) to
  417. * indicate a negative value. The resulting <code>long</code>
  418. * value is returned, exactly as if the argument and the radix
  419. * <code>10</code> were given as arguments to the {@link
  420. * #parseLong(java.lang.String, int)} method.
  421. * <p>
  422. * Note that neither the character <code>L</code>
  423. * (<code>'\u004C'</code>) nor <code>l</code>
  424. * (<code>'\u006C'</code>) is permitted to appear at the end
  425. * of the string as a type indicator, as would be permitted in
  426. * Java programming language source code.
  427. *
  428. * @param s a <code>String</code> containing the <code>long</code>
  429. * representation to be parsed
  430. * @return the <code>long</code> represented by the argument in
  431. * decimal.
  432. * @exception NumberFormatException if the string does not contain a
  433. * parsable <code>long</code>.
  434. */
  435. public static long parseLong(String s) throws NumberFormatException {
  436. return parseLong(s, 10);
  437. }
  438. /**
  439. * Returns a <code>Long</code> object holding the value
  440. * extracted from the specified <code>String</code> when parsed
  441. * with the radix given by the second argument. The first
  442. * argument is interpreted as representing a signed
  443. * <code>long</code> in the radix specified by the second
  444. * argument, exactly as if the arguments were given to the {@link
  445. * #parseLong(java.lang.String, int)} method. The result is a
  446. * <code>Long</code> object that represents the <code>long</code>
  447. * value specified by the string.
  448. * <p>
  449. * In other words, this method returns a <code>Long</code> object equal
  450. * to the value of:
  451. *
  452. * <blockquote><code>
  453. * new Long(Long.parseLong(s, radix))
  454. * </code></blockquote>
  455. *
  456. * @param s the string to be parsed
  457. * @param radix the radix to be used in interpreting <code>s</code>
  458. * @return a <code>Long</code> object holding the value
  459. * represented by the string argument in the specified
  460. * radix.
  461. * @exception NumberFormatException If the <code>String</code> does not
  462. * contain a parsable <code>long</code>.
  463. */
  464. public static Long valueOf(String s, int radix) throws NumberFormatException {
  465. return new Long(parseLong(s, radix));
  466. }
  467. /**
  468. * Returns a <code>Long</code> object holding the value
  469. * of the specified <code>String</code>. The argument is
  470. * interpreted as representing a signed decimal <code>long</code>,
  471. * exactly as if the argument were given to the {@link
  472. * #parseLong(java.lang.String)} method. The result is a
  473. * <code>Long</code> object that represents the integer value
  474. * specified by the string.
  475. * <p>
  476. * In other words, this method returns a <code>Long</code> object
  477. * equal to the value of:
  478. *
  479. * <blockquote><pre>
  480. * new Long(Long.parseLong(s))
  481. * </pre></blockquote>
  482. *
  483. * @param s the string to be parsed.
  484. * @return a <code>Long</code> object holding the value
  485. * represented by the string argument.
  486. * @exception NumberFormatException If the string cannot be parsed
  487. * as a <code>long</code>.
  488. */
  489. public static Long valueOf(String s) throws NumberFormatException
  490. {
  491. return new Long(parseLong(s, 10));
  492. }
  493. private static class LongCache {
  494. private LongCache(){}
  495. static final Long cache[] = new Long[-(-128) + 127 + 1];
  496. static {
  497. for(int i = 0; i < cache.length; i++)
  498. cache[i] = new Long(i - 128);
  499. }
  500. }
  501. /**
  502. * Returns a <tt>Long</tt> instance representing the specified
  503. * <tt>long</tt> value.
  504. * If a new <tt>Long</tt> instance is not required, this method
  505. * should generally be used in preference to the constructor
  506. * {@link #Long(long)}, as this method is likely to yield
  507. * significantly better space and time performance by caching
  508. * frequently requested values.
  509. *
  510. * @param l a long value.
  511. * @return a <tt>Long</tt> instance representing <tt>l</tt>.
  512. * @since 1.5
  513. */
  514. public static Long valueOf(long l) {
  515. final int offset = 128;
  516. if (l >= -128 && l <= 127) { // will cache
  517. return LongCache.cache[(int)l + offset];
  518. }
  519. return new Long(l);
  520. }
  521. /**
  522. * Decodes a <code>String</code> into a <code>Long</code>.
  523. * Accepts decimal, hexadecimal, and octal numbers given by the
  524. * following grammar:
  525. *
  526. * <blockquote>
  527. * <dl>
  528. * <dt><i>DecodableString:</i>
  529. * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
  530. * <dd><i>Sign<sub>opt</sub></i> <code>0x</code> <i>HexDigits</i>
  531. * <dd><i>Sign<sub>opt</sub></i> <code>0X</code> <i>HexDigits</i>
  532. * <dd><i>Sign<sub>opt</sub></i> <code>#</code> <i>HexDigits</i>
  533. * <dd><i>Sign<sub>opt</sub></i> <code>0</code> <i>OctalDigits</i>
  534. * <p>
  535. * <dt><i>Sign:</i>
  536. * <dd><code>-</code>
  537. * </dl>
  538. * </blockquote>
  539. *
  540. * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
  541. * are defined in <a href="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#48282">§3.10.1</a>
  542. * of the <a href="http://java.sun.com/docs/books/jls/html/">Java
  543. * Language Specification</a>.
  544. * <p>
  545. * The sequence of characters following an (optional) negative
  546. * sign and/or radix specifier ("<code>0x</code>",
  547. * "<code>0X</code>", "<code>#</code>", or
  548. * leading zero) is parsed as by the <code>Long.parseLong</code>
  549. * method with the indicated radix (10, 16, or 8). This sequence
  550. * of characters must represent a positive value or a {@link
  551. * NumberFormatException} will be thrown. The result is negated
  552. * if first character of the specified <code>String</code> is the
  553. * minus sign. No whitespace characters are permitted in the
  554. * <code>String</code>.
  555. *
  556. * @param nm the <code>String</code> to decode.
  557. * @return a <code>Long</code> object holding the <code>long</code>
  558. * value represented by <code>nm</code>
  559. * @exception NumberFormatException if the <code>String</code> does not
  560. * contain a parsable <code>long</code>.
  561. * @see java.lang.Long#parseLong(String, int)
  562. * @since 1.2
  563. */
  564. public static Long decode(String nm) throws NumberFormatException {
  565. int radix = 10;
  566. int index = 0;
  567. boolean negative = false;
  568. Long result;
  569. // Handle minus sign, if present
  570. if (nm.startsWith("-")) {
  571. negative = true;
  572. index++;
  573. }
  574. // Handle radix specifier, if present
  575. if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
  576. index += 2;
  577. radix = 16;
  578. }
  579. else if (nm.startsWith("#", index)) {
  580. index ++;
  581. radix = 16;
  582. }
  583. else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
  584. index ++;
  585. radix = 8;
  586. }
  587. if (nm.startsWith("-", index))
  588. throw new NumberFormatException("Negative sign in wrong position");
  589. try {
  590. result = Long.valueOf(nm.substring(index), radix);
  591. result = negative ? new Long((long)-result.longValue()) : result;
  592. } catch (NumberFormatException e) {
  593. // If number is Long.MIN_VALUE, we'll end up here. The next line
  594. // handles this case, and causes any genuine format error to be
  595. // rethrown.
  596. String constant = negative ? new String("-" + nm.substring(index))
  597. : nm.substring(index);
  598. result = Long.valueOf(constant, radix);
  599. }
  600. return result;
  601. }
  602. /**
  603. * The value of the <code>Long</code>.
  604. *
  605. * @serial
  606. */
  607. private final long value;
  608. /**
  609. * Constructs a newly allocated <code>Long</code> object that
  610. * represents the specified <code>long</code> argument.
  611. *
  612. * @param value the value to be represented by the
  613. * <code>Long</code> object.
  614. */
  615. public Long(long value) {
  616. this.value = value;
  617. }
  618. /**
  619. * Constructs a newly allocated <code>Long</code> object that
  620. * represents the <code>long</code> value indicated by the
  621. * <code>String</code> parameter. The string is converted to a
  622. * <code>long</code> value in exactly the manner used by the
  623. * <code>parseLong</code> method for radix 10.
  624. *
  625. * @param s the <code>String</code> to be converted to a
  626. * <code>Long</code>.
  627. * @exception NumberFormatException if the <code>String</code> does not
  628. * contain a parsable <code>long</code>.
  629. * @see java.lang.Long#parseLong(java.lang.String, int)
  630. */
  631. public Long(String s) throws NumberFormatException {
  632. this.value = parseLong(s, 10);
  633. }
  634. /**
  635. * Returns the value of this <code>Long</code> as a
  636. * <code>byte</code>.
  637. */
  638. public byte byteValue() {
  639. return (byte)value;
  640. }
  641. /**
  642. * Returns the value of this <code>Long</code> as a
  643. * <code>short</code>.
  644. */
  645. public short shortValue() {
  646. return (short)value;
  647. }
  648. /**
  649. * Returns the value of this <code>Long</code> as an
  650. * <code>int</code>.
  651. */
  652. public int intValue() {
  653. return (int)value;
  654. }
  655. /**
  656. * Returns the value of this <code>Long</code> as a
  657. * <code>long</code> value.
  658. */
  659. public long longValue() {
  660. return (long)value;
  661. }
  662. /**
  663. * Returns the value of this <code>Long</code> as a
  664. * <code>float</code>.
  665. */
  666. public float floatValue() {
  667. return (float)value;
  668. }
  669. /**
  670. * Returns the value of this <code>Long</code> as a
  671. * <code>double</code>.
  672. */
  673. public double doubleValue() {
  674. return (double)value;
  675. }
  676. /**
  677. * Returns a <code>String</code> object representing this
  678. * <code>Long</code>'s value. The value is converted to signed
  679. * decimal representation and returned as a string, exactly as if
  680. * the <code>long</code> value were given as an argument to the
  681. * {@link java.lang.Long#toString(long)} method.
  682. *
  683. * @return a string representation of the value of this object in
  684. * base 10.
  685. */
  686. public String toString() {
  687. return String.valueOf(value);
  688. }
  689. /**
  690. * Returns a hash code for this <code>Long</code>. The result is
  691. * the exclusive OR of the two halves of the primitive
  692. * <code>long</code> value held by this <code>Long</code>
  693. * object. That is, the hashcode is the value of the expression:
  694. * <blockquote><pre>
  695. * (int)(this.longValue()^(this.longValue()>>>32))
  696. * </pre></blockquote>
  697. *
  698. * @return a hash code value for this object.
  699. */
  700. public int hashCode() {
  701. return (int)(value ^ (value >>> 32));
  702. }
  703. /**
  704. * Compares this object to the specified object. The result is
  705. * <code>true</code> if and only if the argument is not
  706. * <code>null</code> and is a <code>Long</code> object that
  707. * contains the same <code>long</code> value as this object.
  708. *
  709. * @param obj the object to compare with.
  710. * @return <code>true</code> if the objects are the same;
  711. * <code>false</code> otherwise.
  712. */
  713. public boolean equals(Object obj) {
  714. if (obj instanceof Long) {
  715. return value == ((Long)obj).longValue();
  716. }
  717. return false;
  718. }
  719. /**
  720. * Determines the <code>long</code> value of the system property
  721. * with the specified name.
  722. * <p>
  723. * The first argument is treated as the name of a system property.
  724. * System properties are accessible through the {@link
  725. * java.lang.System#getProperty(java.lang.String)} method. The
  726. * string value of this property is then interpreted as a
  727. * <code>long</code> value and a <code>Long</code> object
  728. * representing this value is returned. Details of possible
  729. * numeric formats can be found with the definition of
  730. * <code>getProperty</code>.
  731. * <p>
  732. * If there is no property with the specified name, if the
  733. * specified name is empty or <code>null</code>, or if the
  734. * property does not have the correct numeric format, then
  735. * <code>null</code> is returned.
  736. * <p>
  737. * In other words, this method returns a <code>Long</code> object equal to
  738. * the value of:
  739. * <blockquote><code>
  740. * getLong(nm, null)
  741. * </code></blockquote>
  742. *
  743. * @param nm property name.
  744. * @return the <code>Long</code> value of the property.
  745. * @see java.lang.System#getProperty(java.lang.String)
  746. * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
  747. */
  748. public static Long getLong(String nm) {
  749. return getLong(nm, null);
  750. }
  751. /**
  752. * Determines the <code>long</code> value of the system property
  753. * with the specified name.
  754. * <p>
  755. * The first argument is treated as the name of a system property.
  756. * System properties are accessible through the {@link
  757. * java.lang.System#getProperty(java.lang.String)} method. The
  758. * string value of this property is then interpreted as a
  759. * <code>long</code> value and a <code>Long</code> object
  760. * representing this value is returned. Details of possible
  761. * numeric formats can be found with the definition of
  762. * <code>getProperty</code>.
  763. * <p>
  764. * The second argument is the default value. A <code>Long</code> object
  765. * that represents the value of the second argument is returned if there
  766. * is no property of the specified name, if the property does not have
  767. * the correct numeric format, or if the specified name is empty or null.
  768. * <p>
  769. * In other words, this method returns a <code>Long</code> object equal
  770. * to the value of:
  771. * <blockquote><code>
  772. * getLong(nm, new Long(val))
  773. * </code></blockquote>
  774. * but in practice it may be implemented in a manner such as:
  775. * <blockquote><pre>
  776. * Long result = getLong(nm, null);
  777. * return (result == null) ? new Long(val) : result;
  778. * </pre></blockquote>
  779. * to avoid the unnecessary allocation of a <code>Long</code> object when
  780. * the default value is not needed.
  781. *
  782. * @param nm property name.
  783. * @param val default value.
  784. * @return the <code>Long</code> value of the property.
  785. * @see java.lang.System#getProperty(java.lang.String)
  786. * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
  787. */
  788. public static Long getLong(String nm, long val) {
  789. Long result = Long.getLong(nm, null);
  790. return (result == null) ? new Long(val) : result;
  791. }
  792. /**
  793. * Returns the <code>long</code> value of the system property with
  794. * the specified name. The first argument is treated as the name
  795. * of a system property. System properties are accessible through
  796. * the {@link java.lang.System#getProperty(java.lang.String)}
  797. * method. The string value of this property is then interpreted
  798. * as a <code>long</code> value, as per the
  799. * <code>Long.decode</code> method, and a <code>Long</code> object
  800. * representing this value is returned.
  801. * <p><ul>
  802. * <li>If the property value begins with the two ASCII characters
  803. * <code>0x</code> or the ASCII character <code>#</code>, not followed by
  804. * a minus sign, then the rest of it is parsed as a hexadecimal integer
  805. * exactly as for the method {@link #valueOf(java.lang.String, int)}
  806. * with radix 16.
  807. * <li>If the property value begins with the ASCII character
  808. * <code>0</code> followed by another character, it is parsed as
  809. * an octal integer exactly as by the method {@link
  810. * #valueOf(java.lang.String, int)} with radix 8.
  811. * <li>Otherwise the property value is parsed as a decimal
  812. * integer exactly as by the method
  813. * {@link #valueOf(java.lang.String, int)} with radix 10.
  814. * </ul>
  815. * <p>
  816. * Note that, in every case, neither <code>L</code>
  817. * (<code>'\u004C'</code>) nor <code>l</code>
  818. * (<code>'\u006C'</code>) is permitted to appear at the end
  819. * of the property value as a type indicator, as would be
  820. * permitted in Java programming language source code.
  821. * <p>
  822. * The second argument is the default value. The default value is
  823. * returned if there is no property of the specified name, if the
  824. * property does not have the correct numeric format, or if the
  825. * specified name is empty or <code>null</code>.
  826. *
  827. * @param nm property name.
  828. * @param val default value.
  829. * @return the <code>Long</code> value of the property.
  830. * @see java.lang.System#getProperty(java.lang.String)
  831. * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
  832. * @see java.lang.Long#decode
  833. */
  834. public static Long getLong(String nm, Long val) {
  835. String v = null;
  836. try {
  837. v = System.getProperty(nm);
  838. } catch (IllegalArgumentException e) {
  839. } catch (NullPointerException e) {
  840. }
  841. if (v != null) {
  842. try {
  843. return Long.decode(v);
  844. } catch (NumberFormatException e) {
  845. }
  846. }
  847. return val;
  848. }
  849. /**
  850. * Compares two <code>Long</code> objects numerically.
  851. *
  852. * @param anotherLong the <code>Long</code> to be compared.
  853. * @return the value <code>0</code> if this <code>Long</code> is
  854. * equal to the argument <code>Long</code> a value less than
  855. * <code>0</code> if this <code>Long</code> is numerically less
  856. * than the argument <code>Long</code> and a value greater
  857. * than <code>0</code> if this <code>Long</code> is numerically
  858. * greater than the argument <code>Long</code> (signed
  859. * comparison).
  860. * @since 1.2
  861. */
  862. public int compareTo(Long anotherLong) {
  863. long thisVal = this.value;
  864. long anotherVal = anotherLong.value;
  865. return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
  866. }
  867. // Bit Twiddling
  868. /**
  869. * The number of bits used to represent a <tt>long</tt> value in two's
  870. * complement binary form.
  871. *
  872. * @since 1.5
  873. */
  874. public static final int SIZE = 64;
  875. /**
  876. * Returns an <tt>long</tt> value with at most a single one-bit, in the
  877. * position of the highest-order ("leftmost") one-bit in the specified
  878. * <tt>long</tt> value. Returns zero if the specified value has no
  879. * one-bits in its two's complement binary representation, that is, if it
  880. * is equal to zero.
  881. *
  882. * @return an <tt>long</tt> value with a single one-bit, in the position
  883. * of the highest-order one-bit in the specified value, or zero if
  884. * the specified value is itself equal to zero.
  885. * @since 1.5
  886. */
  887. public static long highestOneBit(long i) {
  888. // HD, Figure 3-1
  889. i |= (i >> 1);
  890. i |= (i >> 2);
  891. i |= (i >> 4);
  892. i |= (i >> 8);
  893. i |= (i >> 16);
  894. i |= (i >> 32);
  895. return i - (i >>> 1);
  896. }
  897. /**
  898. * Returns an <tt>long</tt> value with at most a single one-bit, in the
  899. * position of the lowest-order ("rightmost") one-bit in the specified
  900. * <tt>long</tt> value. Returns zero if the specified value has no
  901. * one-bits in its two's complement binary representation, that is, if it
  902. * is equal to zero.
  903. *
  904. * @return an <tt>long</tt> value with a single one-bit, in the position
  905. * of the lowest-order one-bit in the specified value, or zero if
  906. * the specified value is itself equal to zero.
  907. * @since 1.5
  908. */
  909. public static long lowestOneBit(long i) {
  910. // HD, Section 2-1
  911. return i & -i;
  912. }
  913. /**
  914. * Returns the number of zero bits preceding the highest-order
  915. * ("leftmost") one-bit in the two's complement binary representation
  916. * of the specified <tt>long</tt> value. Returns 64 if the
  917. * specified value has no one-bits in its two's complement representation,
  918. * in other words if it is equal to zero.
  919. *
  920. * <p>Note that this method is closely related to the logarithm base 2.
  921. * For all positive <tt>long</tt> values x:
  922. * <ul>
  923. * <li>floor(log<sub>2</sub>(x)) = <tt>63 - numberOfLeadingZeros(x)</tt>
  924. * <li>ceil(log<sub>2</sub>(x)) = <tt>64 - numberOfLeadingZeros(x - 1)</tt>
  925. * </ul>
  926. *
  927. * @return the number of zero bits preceding the highest-order
  928. * ("leftmost") one-bit in the two's complement binary representation
  929. * of the specified <tt>long</tt> value, or 64 if the value
  930. * is equal to zero.
  931. * @since 1.5
  932. */
  933. public static int numberOfLeadingZeros(long i) {
  934. // HD, Figure 5-6
  935. if (i == 0)
  936. return 64;
  937. int n = 1;
  938. int x = (int)(i >>> 32);
  939. if (x == 0) { n += 32; x = (int)i; }
  940. if (x >>> 16 == 0) { n += 16; x <<= 16; }
  941. if (x >>> 24 == 0) { n += 8; x <<= 8; }
  942. if (x >>> 28 == 0) { n += 4; x <<= 4; }
  943. if (x >>> 30 == 0) { n += 2; x <<= 2; }
  944. n -= x >>> 31;
  945. return n;
  946. }
  947. /**
  948. * Returns the number of zero bits following the lowest-order ("rightmost")
  949. * one-bit in the two's complement binary representation of the specified
  950. * <tt>long</tt> value. Returns 64 if the specified value has no
  951. * one-bits in its two's complement representation, in other words if it is
  952. * equal to zero.
  953. *
  954. * @return the number of zero bits following the lowest-order ("rightmost")
  955. * one-bit in the two's complement binary representation of the
  956. * specified <tt>long</tt> value, or 64 if the value is equal
  957. * to zero.
  958. * @since 1.5
  959. */
  960. public static int numberOfTrailingZeros(long i) {
  961. // HD, Figure 5-14
  962. int x, y;
  963. if (i == 0) return 64;
  964. int n = 63;
  965. y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32);
  966. y = x <<16; if (y != 0) { n = n -16; x = y; }
  967. y = x << 8; if (y != 0) { n = n - 8; x = y; }
  968. y = x << 4; if (y != 0) { n = n - 4; x = y; }
  969. y = x << 2; if (y != 0) { n = n - 2; x = y; }
  970. return n - ((x << 1) >>> 31);
  971. }
  972. /**
  973. * Returns the number of one-bits in the two's complement binary
  974. * representation of the specified <tt>long</tt> value. This function is
  975. * sometimes referred to as the <i>population count</i>.
  976. *
  977. * @return the number of one-bits in the two's complement binary
  978. * representation of the specified <tt>long</tt> value.
  979. * @since 1.5
  980. */
  981. public static int bitCount(long i) {
  982. // HD, Figure 5-14
  983. i = i - ((i >>> 1) & 0x5555555555555555L);
  984. i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L);
  985. i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL;
  986. i = i + (i >>> 8);
  987. i = i + (i >>> 16);
  988. i = i + (i >>> 32);
  989. return (int)i & 0x7f;
  990. }
  991. /**
  992. * Returns the value obtained by rotating the two's complement binary
  993. * representation of the specified <tt>long</tt> value left by the
  994. * specified number of bits. (Bits shifted out of the left hand, or
  995. * high-order, side reenter on the right, or low-order.)
  996. *
  997. * <p>Note that left rotation with a negative distance is equivalent to
  998. * right rotation: <tt>rotateLeft(val, -distance) == rotateRight(val,
  999. * distance)</tt>. Note also that rotation by any multiple of 64 is a
  1000. * no-op, so all but the last six bits of the rotation distance can be
  1001. * ignored, even if the distance is negative: <tt>rotateLeft(val,
  1002. * distance) == rotateLeft(val, distance & 0x3F)</tt>.
  1003. *
  1004. * @return the value obtained by rotating the two's complement binary
  1005. * representation of the specified <tt>long</tt> value left by the
  1006. * specified number of bits.
  1007. * @since 1.5
  1008. */
  1009. public static long rotateLeft(long i, int distance) {
  1010. return (i << distance) | (i >>> -distance);
  1011. }
  1012. /**
  1013. * Returns the value obtained by rotating the two's complement binary
  1014. * representation of the specified <tt>long</tt> value right by the
  1015. * specified number of bits. (Bits shifted out of the right hand, or
  1016. * low-order, side reenter on the left, or high-order.)
  1017. *
  1018. * <p>Note that right rotation with a negative distance is equivalent to
  1019. * left rotation: <tt>rotateRight(val, -distance) == rotateLeft(val,
  1020. * distance)</tt>. Note also that rotation by any multiple of 64 is a
  1021. * no-op, so all but the last six bits of the rotation distance can be
  1022. * ignored, even if the distance is negative: <tt>rotateRight(val,
  1023. * distance) == rotateRight(val, distance & 0x3F)</tt>.
  1024. *
  1025. * @return the value obtained by rotating the two's complement binary
  1026. * representation of the specified <tt>long</tt> value right by the
  1027. * specified number of bits.
  1028. * @since 1.5
  1029. */
  1030. public static long rotateRight(long i, int distance) {
  1031. return (i >>> distance) | (i << -distance);
  1032. }
  1033. /**
  1034. * Returns the value obtained by reversing the order of the bits in the
  1035. * two's complement binary representation of the specified <tt>long</tt>
  1036. * value.
  1037. *
  1038. * @return the value obtained by reversing order of the bits in the
  1039. * specified <tt>long</tt> value.
  1040. * @since 1.5
  1041. */
  1042. public static long reverse(long i) {
  1043. // HD, Figure 7-1
  1044. i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L;
  1045. i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L;
  1046. i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL;
  1047. i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
  1048. i = (i << 48) | ((i & 0xffff0000L) << 16) |
  1049. ((i >>> 16) & 0xffff0000L) | (i >>> 48);
  1050. return i;
  1051. }
  1052. /**
  1053. * Returns the signum function of the specified <tt>long</tt> value. (The
  1054. * return value is -1 if the specified value is negative; 0 if the
  1055. * specified value is zero; and 1 if the specified value is positive.)
  1056. *
  1057. * @return the signum function of the specified <tt>long</tt> value.
  1058. * @since 1.5
  1059. */
  1060. public static int signum(long i) {
  1061. // HD, Section 2-7
  1062. return (int) ((i >> 63) | (-i >>> 63));
  1063. }
  1064. /**
  1065. * Returns the value obtained by reversing the order of the bytes in the
  1066. * two's complement representation of the specified <tt>long</tt> value.
  1067. *
  1068. * @return the value obtained by reversing the bytes in the specified
  1069. * <tt>long</tt> value.
  1070. * @since 1.5
  1071. */
  1072. public static long reverseBytes(long i) {
  1073. i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
  1074. return (i << 48) | ((i & 0xffff0000L) << 16) |
  1075. ((i >>> 16) & 0xffff0000L) | (i >>> 48);
  1076. }
  1077. /** use serialVersionUID from JDK 1.0.2 for interoperability */
  1078. private static final long serialVersionUID = 4290774380558885855L;
  1079. }