Long.java 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. /* Long.java -- object wrapper for long
  2. Copyright (C) 1998, 1999, 2001, 2002, 2004, 2005 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.lang;
  32. /**
  33. * Instances of class <code>Long</code> represent primitive
  34. * <code>long</code> values.
  35. *
  36. * Additionally, this class provides various helper functions and variables
  37. * related to longs.
  38. *
  39. * @author Paul Fisher
  40. * @author John Keiser
  41. * @author Warren Levy
  42. * @author Eric Blake (ebb9@email.byu.edu)
  43. * @author Tom Tromey (tromey@redhat.com)
  44. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  45. * @author Ian Rogers
  46. * @since 1.0
  47. * @status updated to 1.5
  48. */
  49. public final class Long extends Number implements Comparable<Long>
  50. {
  51. /**
  52. * Compatible with JDK 1.0.2+.
  53. */
  54. private static final long serialVersionUID = 4290774380558885855L;
  55. /**
  56. * The minimum value a <code>long</code> can represent is
  57. * -9223372036854775808L (or -2<sup>63</sup>).
  58. */
  59. public static final long MIN_VALUE = 0x8000000000000000L;
  60. /**
  61. * The maximum value a <code>long</code> can represent is
  62. * 9223372036854775807 (or 2<sup>63</sup> - 1).
  63. */
  64. public static final long MAX_VALUE = 0x7fffffffffffffffL;
  65. /**
  66. * The primitive type <code>long</code> is represented by this
  67. * <code>Class</code> object.
  68. * @since 1.1
  69. */
  70. public static final Class<Long> TYPE = (Class<Long>) VMClassLoader.getPrimitiveClass ('J');
  71. /**
  72. * The number of bits needed to represent a <code>long</code>.
  73. * @since 1.5
  74. */
  75. public static final int SIZE = 64;
  76. // This caches some Long values, and is used by boxing
  77. // conversions via valueOf(). We cache at least -128..127;
  78. // these constants control how much we actually cache.
  79. private static final int MIN_CACHE = -128;
  80. private static final int MAX_CACHE = 127;
  81. private static final Long[] longCache = new Long[MAX_CACHE - MIN_CACHE + 1];
  82. static
  83. {
  84. for (int i=MIN_CACHE; i <= MAX_CACHE; i++)
  85. longCache[i - MIN_CACHE] = new Long(i);
  86. }
  87. /**
  88. * The immutable value of this Long.
  89. *
  90. * @serial the wrapped long
  91. */
  92. private final long value;
  93. /**
  94. * Create a <code>Long</code> object representing the value of the
  95. * <code>long</code> argument.
  96. *
  97. * @param value the value to use
  98. */
  99. public Long(long value)
  100. {
  101. this.value = value;
  102. }
  103. /**
  104. * Create a <code>Long</code> object representing the value of the
  105. * argument after conversion to a <code>long</code>.
  106. *
  107. * @param s the string to convert
  108. * @throws NumberFormatException if the String does not contain a long
  109. * @see #valueOf(String)
  110. */
  111. public Long(String s)
  112. {
  113. value = parseLong(s, 10, false);
  114. }
  115. /**
  116. * Return the size of a string large enough to hold the given number
  117. *
  118. * @param num the number we want the string length for (must be positive)
  119. * @param radix the radix (base) that will be used for the string
  120. * @return a size sufficient for a string of num
  121. */
  122. private static int stringSize(long num, int radix) {
  123. int exp;
  124. if (radix < 4)
  125. {
  126. exp = 1;
  127. }
  128. else if (radix < 8)
  129. {
  130. exp = 2;
  131. }
  132. else if (radix < 16)
  133. {
  134. exp = 3;
  135. }
  136. else if (radix < 32)
  137. {
  138. exp = 4;
  139. }
  140. else
  141. {
  142. exp = 5;
  143. }
  144. int size=0;
  145. do
  146. {
  147. num >>>= exp;
  148. size++;
  149. }
  150. while(num != 0);
  151. return size;
  152. }
  153. /**
  154. * Converts the <code>long</code> to a <code>String</code> using
  155. * the specified radix (base). If the radix exceeds
  156. * <code>Character.MIN_RADIX</code> or <code>Character.MAX_RADIX</code>, 10
  157. * is used instead. If the result is negative, the leading character is
  158. * '-' ('\\u002D'). The remaining characters come from
  159. * <code>Character.forDigit(digit, radix)</code> ('0'-'9','a'-'z').
  160. *
  161. * @param num the <code>long</code> to convert to <code>String</code>
  162. * @param radix the radix (base) to use in the conversion
  163. * @return the <code>String</code> representation of the argument
  164. */
  165. public static String toString(long num, int radix)
  166. {
  167. if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
  168. radix = 10;
  169. // Is the value negative?
  170. boolean isNeg = num < 0;
  171. // Is the string a single character?
  172. if (!isNeg && num < radix)
  173. return new String(digits, (int)num, 1, true);
  174. // Compute string size and allocate buffer
  175. // account for a leading '-' if the value is negative
  176. int size;
  177. int i;
  178. char[] buffer;
  179. if (isNeg)
  180. {
  181. num = -num;
  182. // When the value is MIN_VALUE, it overflows when made positive
  183. if (num < 0)
  184. {
  185. i = size = stringSize(MAX_VALUE, radix) + 2;
  186. buffer = new char[size];
  187. buffer[--i] = digits[(int) (-(num + radix) % radix)];
  188. num = -(num / radix);
  189. }
  190. else
  191. {
  192. i = size = stringSize(num, radix) + 1;
  193. buffer = new char[size];
  194. }
  195. }
  196. else
  197. {
  198. i = size = stringSize(num, radix);
  199. buffer = new char[size];
  200. }
  201. do
  202. {
  203. buffer[--i] = digits[(int) (num % radix)];
  204. num /= radix;
  205. }
  206. while (num > 0);
  207. if (isNeg)
  208. buffer[--i] = '-';
  209. // Package constructor avoids an array copy.
  210. return new String(buffer, i, size - i, true);
  211. }
  212. /**
  213. * Converts the <code>long</code> to a <code>String</code> assuming it is
  214. * unsigned in base 16.
  215. *
  216. * @param l the <code>long</code> to convert to <code>String</code>
  217. * @return the <code>String</code> representation of the argument
  218. */
  219. public static String toHexString(long l)
  220. {
  221. return toUnsignedString(l, 4);
  222. }
  223. /**
  224. * Converts the <code>long</code> to a <code>String</code> assuming it is
  225. * unsigned in base 8.
  226. *
  227. * @param l the <code>long</code> to convert to <code>String</code>
  228. * @return the <code>String</code> representation of the argument
  229. */
  230. public static String toOctalString(long l)
  231. {
  232. return toUnsignedString(l, 3);
  233. }
  234. /**
  235. * Converts the <code>long</code> to a <code>String</code> assuming it is
  236. * unsigned in base 2.
  237. *
  238. * @param l the <code>long</code> to convert to <code>String</code>
  239. * @return the <code>String</code> representation of the argument
  240. */
  241. public static String toBinaryString(long l)
  242. {
  243. return toUnsignedString(l, 1);
  244. }
  245. /**
  246. * Converts the <code>long</code> to a <code>String</code> and assumes
  247. * a radix of 10.
  248. *
  249. * @param num the <code>long</code> to convert to <code>String</code>
  250. * @return the <code>String</code> representation of the argument
  251. * @see #toString(long, int)
  252. */
  253. public static String toString(long num)
  254. {
  255. return toString(num, 10);
  256. }
  257. /**
  258. * Converts the specified <code>String</code> into an <code>int</code>
  259. * using the specified radix (base). The string must not be <code>null</code>
  260. * or empty. It may begin with an optional '-', which will negate the answer,
  261. * provided that there are also valid digits. Each digit is parsed as if by
  262. * <code>Character.digit(d, radix)</code>, and must be in the range
  263. * <code>0</code> to <code>radix - 1</code>. Finally, the result must be
  264. * within <code>MIN_VALUE</code> to <code>MAX_VALUE</code>, inclusive.
  265. * Unlike Double.parseDouble, you may not have a leading '+'; and 'l' or
  266. * 'L' as the last character is only valid in radices 22 or greater, where
  267. * it is a digit and not a type indicator.
  268. *
  269. * @param str the <code>String</code> to convert
  270. * @param radix the radix (base) to use in the conversion
  271. * @return the <code>String</code> argument converted to <code>long</code>
  272. * @throws NumberFormatException if <code>s</code> cannot be parsed as a
  273. * <code>long</code>
  274. */
  275. public static long parseLong(String str, int radix)
  276. {
  277. return parseLong(str, radix, false);
  278. }
  279. /**
  280. * Converts the specified <code>String</code> into a <code>long</code>.
  281. * This function assumes a radix of 10.
  282. *
  283. * @param s the <code>String</code> to convert
  284. * @return the <code>int</code> value of <code>s</code>
  285. * @throws NumberFormatException if <code>s</code> cannot be parsed as a
  286. * <code>long</code>
  287. * @see #parseLong(String, int)
  288. */
  289. public static long parseLong(String s)
  290. {
  291. return parseLong(s, 10, false);
  292. }
  293. /**
  294. * Creates a new <code>Long</code> object using the <code>String</code>
  295. * and specified radix (base).
  296. *
  297. * @param s the <code>String</code> to convert
  298. * @param radix the radix (base) to convert with
  299. * @return the new <code>Long</code>
  300. * @throws NumberFormatException if <code>s</code> cannot be parsed as a
  301. * <code>long</code>
  302. * @see #parseLong(String, int)
  303. */
  304. public static Long valueOf(String s, int radix)
  305. {
  306. return valueOf(parseLong(s, radix, false));
  307. }
  308. /**
  309. * Creates a new <code>Long</code> object using the <code>String</code>,
  310. * assuming a radix of 10.
  311. *
  312. * @param s the <code>String</code> to convert
  313. * @return the new <code>Long</code>
  314. * @throws NumberFormatException if <code>s</code> cannot be parsed as a
  315. * <code>long</code>
  316. * @see #Long(String)
  317. * @see #parseLong(String)
  318. */
  319. public static Long valueOf(String s)
  320. {
  321. return valueOf(parseLong(s, 10, false));
  322. }
  323. /**
  324. * Returns a <code>Long</code> object wrapping the value.
  325. *
  326. * @param val the value to wrap
  327. * @return the <code>Long</code>
  328. * @since 1.5
  329. */
  330. public static Long valueOf(long val)
  331. {
  332. if (val < MIN_CACHE || val > MAX_CACHE)
  333. return new Long(val);
  334. else
  335. return longCache[((int)val) - MIN_CACHE];
  336. }
  337. /**
  338. * Convert the specified <code>String</code> into a <code>Long</code>.
  339. * The <code>String</code> may represent decimal, hexadecimal, or
  340. * octal numbers.
  341. *
  342. * <p>The extended BNF grammar is as follows:<br>
  343. * <pre>
  344. * <em>DecodableString</em>:
  345. * ( [ <code>-</code> ] <em>DecimalNumber</em> )
  346. * | ( [ <code>-</code> ] ( <code>0x</code> | <code>0X</code>
  347. * | <code>#</code> ) <em>HexDigit</em> { <em>HexDigit</em> } )
  348. * | ( [ <code>-</code> ] <code>0</code> { <em>OctalDigit</em> } )
  349. * <em>DecimalNumber</em>:
  350. * <em>DecimalDigit except '0'</em> { <em>DecimalDigit</em> }
  351. * <em>DecimalDigit</em>:
  352. * <em>Character.digit(d, 10) has value 0 to 9</em>
  353. * <em>OctalDigit</em>:
  354. * <em>Character.digit(d, 8) has value 0 to 7</em>
  355. * <em>DecimalDigit</em>:
  356. * <em>Character.digit(d, 16) has value 0 to 15</em>
  357. * </pre>
  358. * Finally, the value must be in the range <code>MIN_VALUE</code> to
  359. * <code>MAX_VALUE</code>, or an exception is thrown. Note that you cannot
  360. * use a trailing 'l' or 'L', unlike in Java source code.
  361. *
  362. * @param str the <code>String</code> to interpret
  363. * @return the value of the String as a <code>Long</code>
  364. * @throws NumberFormatException if <code>s</code> cannot be parsed as a
  365. * <code>long</code>
  366. * @throws NullPointerException if <code>s</code> is null
  367. * @since 1.2
  368. */
  369. public static Long decode(String str)
  370. {
  371. return valueOf(parseLong(str, 10, true));
  372. }
  373. /**
  374. * Return the value of this <code>Long</code> as a <code>byte</code>.
  375. *
  376. * @return the byte value
  377. */
  378. public byte byteValue()
  379. {
  380. return (byte) value;
  381. }
  382. /**
  383. * Return the value of this <code>Long</code> as a <code>short</code>.
  384. *
  385. * @return the short value
  386. */
  387. public short shortValue()
  388. {
  389. return (short) value;
  390. }
  391. /**
  392. * Return the value of this <code>Long</code> as an <code>int</code>.
  393. *
  394. * @return the int value
  395. */
  396. public int intValue()
  397. {
  398. return (int) value;
  399. }
  400. /**
  401. * Return the value of this <code>Long</code>.
  402. *
  403. * @return the long value
  404. */
  405. public long longValue()
  406. {
  407. return value;
  408. }
  409. /**
  410. * Return the value of this <code>Long</code> as a <code>float</code>.
  411. *
  412. * @return the float value
  413. */
  414. public float floatValue()
  415. {
  416. return value;
  417. }
  418. /**
  419. * Return the value of this <code>Long</code> as a <code>double</code>.
  420. *
  421. * @return the double value
  422. */
  423. public double doubleValue()
  424. {
  425. return value;
  426. }
  427. /**
  428. * Converts the <code>Long</code> value to a <code>String</code> and
  429. * assumes a radix of 10.
  430. *
  431. * @return the <code>String</code> representation
  432. */
  433. public String toString()
  434. {
  435. return toString(value, 10);
  436. }
  437. /**
  438. * Return a hashcode representing this Object. <code>Long</code>'s hash
  439. * code is calculated by <code>(int) (value ^ (value &gt;&gt; 32))</code>.
  440. *
  441. * @return this Object's hash code
  442. */
  443. public int hashCode()
  444. {
  445. return (int) (value ^ (value >>> 32));
  446. }
  447. /**
  448. * Returns <code>true</code> if <code>obj</code> is an instance of
  449. * <code>Long</code> and represents the same long value.
  450. *
  451. * @param obj the object to compare
  452. * @return whether these Objects are semantically equal
  453. */
  454. public boolean equals(Object obj)
  455. {
  456. return obj instanceof Long && value == ((Long) obj).value;
  457. }
  458. /**
  459. * Get the specified system property as a <code>Long</code>. The
  460. * <code>decode()</code> method will be used to interpret the value of
  461. * the property.
  462. *
  463. * @param nm the name of the system property
  464. * @return the system property as a <code>Long</code>, or null if the
  465. * property is not found or cannot be decoded
  466. * @throws SecurityException if accessing the system property is forbidden
  467. * @see System#getProperty(String)
  468. * @see #decode(String)
  469. */
  470. public static Long getLong(String nm)
  471. {
  472. return getLong(nm, null);
  473. }
  474. /**
  475. * Get the specified system property as a <code>Long</code>, or use a
  476. * default <code>long</code> value if the property is not found or is not
  477. * decodable. The <code>decode()</code> method will be used to interpret
  478. * the value of the property.
  479. *
  480. * @param nm the name of the system property
  481. * @param val the default value
  482. * @return the value of the system property, or the default
  483. * @throws SecurityException if accessing the system property is forbidden
  484. * @see System#getProperty(String)
  485. * @see #decode(String)
  486. */
  487. public static Long getLong(String nm, long val)
  488. {
  489. Long result = getLong(nm, null);
  490. return result == null ? valueOf(val) : result;
  491. }
  492. /**
  493. * Get the specified system property as a <code>Long</code>, or use a
  494. * default <code>Long</code> value if the property is not found or is
  495. * not decodable. The <code>decode()</code> method will be used to
  496. * interpret the value of the property.
  497. *
  498. * @param nm the name of the system property
  499. * @param def the default value
  500. * @return the value of the system property, or the default
  501. * @throws SecurityException if accessing the system property is forbidden
  502. * @see System#getProperty(String)
  503. * @see #decode(String)
  504. */
  505. public static Long getLong(String nm, Long def)
  506. {
  507. if (nm == null || "".equals(nm))
  508. return def;
  509. nm = System.getProperty(nm);
  510. if (nm == null)
  511. return def;
  512. try
  513. {
  514. return decode(nm);
  515. }
  516. catch (NumberFormatException e)
  517. {
  518. return def;
  519. }
  520. }
  521. /**
  522. * Compare two Longs numerically by comparing their <code>long</code>
  523. * values. The result is positive if the first is greater, negative if the
  524. * second is greater, and 0 if the two are equal.
  525. *
  526. * @param l the Long to compare
  527. * @return the comparison
  528. * @since 1.2
  529. */
  530. public int compareTo(Long l)
  531. {
  532. if (value == l.value)
  533. return 0;
  534. // Returns just -1 or 1 on inequality; doing math might overflow the long.
  535. return value > l.value ? 1 : -1;
  536. }
  537. /**
  538. * Compares two unboxed long values.
  539. * The result is positive if the first is greater, negative if the second
  540. * is greater, and 0 if the two are equal.
  541. *
  542. * @param x First value to compare.
  543. * @param y Second value to compare.
  544. *
  545. * @return positive int if the first value is greater, negative if the second
  546. * is greater, and 0 if the two are equal.
  547. * @since 1.7
  548. */
  549. public static int compare(long x, long y)
  550. {
  551. return Long.valueOf(x).compareTo(Long.valueOf(y));
  552. }
  553. /**
  554. * Return the number of bits set in x.
  555. * @param x value to examine
  556. * @since 1.5
  557. */
  558. public static int bitCount(long x)
  559. {
  560. // Successively collapse alternating bit groups into a sum.
  561. x = ((x >> 1) & 0x5555555555555555L) + (x & 0x5555555555555555L);
  562. x = ((x >> 2) & 0x3333333333333333L) + (x & 0x3333333333333333L);
  563. int v = (int) ((x >>> 32) + x);
  564. v = ((v >> 4) & 0x0f0f0f0f) + (v & 0x0f0f0f0f);
  565. v = ((v >> 8) & 0x00ff00ff) + (v & 0x00ff00ff);
  566. return ((v >> 16) & 0x0000ffff) + (v & 0x0000ffff);
  567. }
  568. /**
  569. * Rotate x to the left by distance bits.
  570. * @param x the value to rotate
  571. * @param distance the number of bits by which to rotate
  572. * @since 1.5
  573. */
  574. public static long rotateLeft(long x, int distance)
  575. {
  576. // This trick works because the shift operators implicitly mask
  577. // the shift count.
  578. return (x << distance) | (x >>> - distance);
  579. }
  580. /**
  581. * Rotate x to the right by distance bits.
  582. * @param x the value to rotate
  583. * @param distance the number of bits by which to rotate
  584. * @since 1.5
  585. */
  586. public static long rotateRight(long x, int distance)
  587. {
  588. // This trick works because the shift operators implicitly mask
  589. // the shift count.
  590. return (x << - distance) | (x >>> distance);
  591. }
  592. /**
  593. * Find the highest set bit in value, and return a new value
  594. * with only that bit set.
  595. * @param value the value to examine
  596. * @since 1.5
  597. */
  598. public static long highestOneBit(long value)
  599. {
  600. value |= value >>> 1;
  601. value |= value >>> 2;
  602. value |= value >>> 4;
  603. value |= value >>> 8;
  604. value |= value >>> 16;
  605. value |= value >>> 32;
  606. return value ^ (value >>> 1);
  607. }
  608. /**
  609. * Return the number of leading zeros in value.
  610. * @param value the value to examine
  611. * @since 1.5
  612. */
  613. public static int numberOfLeadingZeros(long value)
  614. {
  615. value |= value >>> 1;
  616. value |= value >>> 2;
  617. value |= value >>> 4;
  618. value |= value >>> 8;
  619. value |= value >>> 16;
  620. value |= value >>> 32;
  621. return bitCount(~value);
  622. }
  623. /**
  624. * Find the lowest set bit in value, and return a new value
  625. * with only that bit set.
  626. * @param value the value to examine
  627. * @since 1.5
  628. */
  629. public static long lowestOneBit(long value)
  630. {
  631. // Classic assembly trick.
  632. return value & - value;
  633. }
  634. /**
  635. * Find the number of trailing zeros in value.
  636. * @param value the value to examine
  637. * @since 1.5
  638. */
  639. public static int numberOfTrailingZeros(long value)
  640. {
  641. return bitCount((value & -value) - 1);
  642. }
  643. /**
  644. * Return 1 if x is positive, -1 if it is negative, and 0 if it is
  645. * zero.
  646. * @param x the value to examine
  647. * @since 1.5
  648. */
  649. public static int signum(long x)
  650. {
  651. return (int) ((x >> 63) | (-x >>> 63));
  652. // The LHS propagates the sign bit through every bit in the word;
  653. // if X < 0, every bit is set to 1, else 0. if X > 0, the RHS
  654. // negates x and shifts the resulting 1 in the sign bit to the
  655. // LSB, leaving every other bit 0.
  656. // Hacker's Delight, Section 2-7
  657. }
  658. /**
  659. * Reverse the bytes in val.
  660. * @since 1.5
  661. */
  662. public static long reverseBytes(long val)
  663. {
  664. int hi = Integer.reverseBytes((int) val);
  665. int lo = Integer.reverseBytes((int) (val >>> 32));
  666. return (((long) hi) << 32) | lo;
  667. }
  668. /**
  669. * Reverse the bits in val.
  670. * @since 1.5
  671. */
  672. public static long reverse(long val)
  673. {
  674. long hi = Integer.reverse((int) val) & 0xffffffffL;
  675. long lo = Integer.reverse((int) (val >>> 32)) & 0xffffffffL;
  676. return (hi << 32) | lo;
  677. }
  678. /**
  679. * Helper for converting unsigned numbers to String.
  680. *
  681. * @param num the number
  682. * @param exp log2(digit) (ie. 1, 3, or 4 for binary, oct, hex)
  683. */
  684. private static String toUnsignedString(long num, int exp)
  685. {
  686. // Compute string length
  687. int size = 1;
  688. long copy = num >>> exp;
  689. while (copy != 0)
  690. {
  691. size++;
  692. copy >>>= exp;
  693. }
  694. // Quick path for single character strings
  695. if (size == 1)
  696. return new String(digits, (int)num, 1, true);
  697. // Encode into buffer
  698. int mask = (1 << exp) - 1;
  699. char[] buffer = new char[size];
  700. int i = size;
  701. do
  702. {
  703. buffer[--i] = digits[(int) num & mask];
  704. num >>>= exp;
  705. }
  706. while (num != 0);
  707. // Package constructor avoids an array copy.
  708. return new String(buffer, i, size - i, true);
  709. }
  710. /**
  711. * Helper for parsing longs.
  712. *
  713. * @param str the string to parse
  714. * @param radix the radix to use, must be 10 if decode is true
  715. * @param decode if called from decode
  716. * @return the parsed long value
  717. * @throws NumberFormatException if there is an error
  718. * @throws NullPointerException if decode is true and str is null
  719. * @see #parseLong(String, int)
  720. * @see #decode(String)
  721. */
  722. private static long parseLong(String str, int radix, boolean decode)
  723. {
  724. if (! decode && str == null)
  725. throw new NumberFormatException();
  726. int index = 0;
  727. int len = str.length();
  728. boolean isNeg = false;
  729. if (len == 0)
  730. throw new NumberFormatException();
  731. int ch = str.charAt(index);
  732. if (ch == '-')
  733. {
  734. if (len == 1)
  735. throw new NumberFormatException();
  736. isNeg = true;
  737. ch = str.charAt(++index);
  738. }
  739. if (decode)
  740. {
  741. if (ch == '0')
  742. {
  743. if (++index == len)
  744. return 0;
  745. if ((str.charAt(index) & ~('x' ^ 'X')) == 'X')
  746. {
  747. radix = 16;
  748. index++;
  749. }
  750. else
  751. radix = 8;
  752. }
  753. else if (ch == '#')
  754. {
  755. radix = 16;
  756. index++;
  757. }
  758. }
  759. if (index == len)
  760. throw new NumberFormatException();
  761. long max = MAX_VALUE / radix;
  762. // We can't directly write `max = (MAX_VALUE + 1) / radix'.
  763. // So instead we fake it.
  764. if (isNeg && MAX_VALUE % radix == radix - 1)
  765. ++max;
  766. long val = 0;
  767. while (index < len)
  768. {
  769. if (val < 0 || val > max)
  770. throw new NumberFormatException();
  771. ch = Character.digit(str.charAt(index++), radix);
  772. val = val * radix + ch;
  773. if (ch < 0 || (val < 0 && (! isNeg || val != MIN_VALUE)))
  774. throw new NumberFormatException();
  775. }
  776. return isNeg ? -val : val;
  777. }
  778. }