1 /*
2 * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package java.lang;
27
28 /**
29 * The {@code Long} class wraps a value of the primitive type {@code
30 * long} in an object. An object of type {@code Long} contains a
31 * single field whose type is {@code long}.
32 *
33 * <p> In addition, this class provides several methods for converting
34 * a {@code long} to a {@code String} and a {@code String} to a {@code
35 * long}, as well as other constants and methods useful when dealing
36 * with a {@code long}.
37 *
38 * <p>Implementation note: The implementations of the "bit twiddling"
39 * methods (such as {@link #highestOneBit(long) highestOneBit} and
40 * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are
41 * based on material from Henry S. Warren, Jr.'s <i>Hacker's
42 * Delight</i>, (Addison Wesley, 2002).
43 *
44 * @author Lee Boynton
45 * @author Arthur van Hoff
46 * @author Josh Bloch
47 * @author Joseph D. Darcy
123 boolean negative = (i < 0);
124
125 if (!negative) {
126 i = -i;
127 }
128
129 while (i <= -radix) {
130 buf[charPos--] = Integer.digits[(int)(-(i % radix))];
131 i = i / radix;
132 }
133 buf[charPos] = Integer.digits[(int)(-i)];
134
135 if (negative) {
136 buf[--charPos] = '-';
137 }
138
139 return new String(buf, charPos, (65 - charPos));
140 }
141
142 /**
143 * Returns a string representation of the {@code long}
144 * argument as an unsigned integer in base 16.
145 *
146 * <p>The unsigned {@code long} value is the argument plus
147 * 2<sup>64</sup> if the argument is negative; otherwise, it is
148 * equal to the argument. This value is converted to a string of
149 * ASCII digits in hexadecimal (base 16) with no extra
150 * leading {@code 0}s. If the unsigned magnitude is zero, it
151 * is represented by a single zero character {@code '0'}
152 * (<code>'\u0030'</code>); otherwise, the first character of
153 * the representation of the unsigned magnitude will not be the
154 * zero character. The following characters are used as
155 * hexadecimal digits:
156 *
157 * <blockquote>
158 * {@code 0123456789abcdef}
159 * </blockquote>
160 *
161 * These are the characters <code>'\u0030'</code> through
162 * <code>'\u0039'</code> and <code>'\u0061'</code> through
163 * <code>'\u0066'</code>. If uppercase letters are desired,
164 * the {@link java.lang.String#toUpperCase()} method may be called
165 * on the result:
166 *
167 * <blockquote>
168 * {@code Long.toHexString(n).toUpperCase()}
169 * </blockquote>
170 *
171 * @param i a {@code long} to be converted to a string.
172 * @return the string representation of the unsigned {@code long}
173 * value represented by the argument in hexadecimal
174 * (base 16).
175 * @since JDK 1.0.2
176 */
177 public static String toHexString(long i) {
178 return toUnsignedString(i, 4);
179 }
180
181 /**
182 * Returns a string representation of the {@code long}
183 * argument as an unsigned integer in base 8.
184 *
185 * <p>The unsigned {@code long} value is the argument plus
186 * 2<sup>64</sup> if the argument is negative; otherwise, it is
187 * equal to the argument. This value is converted to a string of
188 * ASCII digits in octal (base 8) with no extra leading
189 * {@code 0}s.
190 *
191 * <p>If the unsigned magnitude is zero, it is represented by a
192 * single zero character {@code '0'}
193 * (<code>'\u0030'</code>); otherwise, the first character of
194 * the representation of the unsigned magnitude will not be the
195 * zero character. The following characters are used as octal
196 * digits:
197 *
198 * <blockquote>
199 * {@code 01234567}
200 * </blockquote>
201 *
202 * These are the characters <code>'\u0030'</code> through
203 * <code>'\u0037'</code>.
204 *
205 * @param i a {@code long} to be converted to a string.
206 * @return the string representation of the unsigned {@code long}
207 * value represented by the argument in octal (base 8).
208 * @since JDK 1.0.2
209 */
210 public static String toOctalString(long i) {
211 return toUnsignedString(i, 3);
212 }
213
214 /**
215 * Returns a string representation of the {@code long}
216 * argument as an unsigned integer in base 2.
217 *
218 * <p>The unsigned {@code long} value is the argument plus
219 * 2<sup>64</sup> if the argument is negative; otherwise, it is
220 * equal to the argument. This value is converted to a string of
221 * ASCII digits in binary (base 2) with no extra leading
222 * {@code 0}s. If the unsigned magnitude is zero, it is
223 * represented by a single zero character {@code '0'}
224 * (<code>'\u0030'</code>); otherwise, the first character of
225 * the representation of the unsigned magnitude will not be the
226 * zero character. The characters {@code '0'}
227 * (<code>'\u0030'</code>) and {@code '1'}
228 * (<code>'\u0031'</code>) are used as binary digits.
229 *
230 * @param i a {@code long} to be converted to a string.
231 * @return the string representation of the unsigned {@code long}
232 * value represented by the argument in binary (base 2).
233 * @since JDK 1.0.2
234 */
235 public static String toBinaryString(long i) {
236 return toUnsignedString(i, 1);
237 }
238
239 /**
240 * Convert the integer to an unsigned number.
241 */
242 private static String toUnsignedString(long i, int shift) {
243 char[] buf = new char[64];
244 int charPos = 64;
245 int radix = 1 << shift;
246 long mask = radix - 1;
247 do {
248 buf[--charPos] = Integer.digits[(int)(i & mask)];
249 i >>>= shift;
250 } while (i != 0);
251 return new String(buf, charPos, (64 - charPos));
252 }
253
254 /**
255 * Returns a {@code String} object representing the specified
256 * {@code long}. The argument is converted to signed decimal
257 * representation and returned as a string, exactly as if the
258 * argument and the radix 10 were given as arguments to the {@link
259 * #toString(long, int)} method.
260 *
261 * @param i a {@code long} to be converted.
262 * @return a string representation of the argument in base 10.
263 */
264 public static String toString(long i) {
265 if (i == Long.MIN_VALUE)
266 return "-9223372036854775808";
267 int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
268 char[] buf = new char[size];
269 getChars(i, size, buf);
270 return new String(0, size, buf);
271 }
272
273 /**
274 * Places characters representing the integer i into the
275 * character array buf. The characters are placed into
276 * the buffer backwards starting with the least significant
277 * digit at the specified index (exclusive), and working
278 * backwards from there.
279 *
280 * Will fail if i == Long.MIN_VALUE
281 */
282 static void getChars(long i, int index, char[] buf) {
283 long q;
284 int r;
285 int charPos = index;
286 char sign = 0;
287
288 if (i < 0) {
289 sign = '-';
290 i = -i;
291 }
292
293 // Get 2 digits/iteration using longs until quotient fits into an int
468 * #parseLong(java.lang.String, int)} method.
469 *
470 * <p>Note that neither the character {@code L}
471 * (<code>'\u004C'</code>) nor {@code l}
472 * (<code>'\u006C'</code>) is permitted to appear at the end
473 * of the string as a type indicator, as would be permitted in
474 * Java programming language source code.
475 *
476 * @param s a {@code String} containing the {@code long}
477 * representation to be parsed
478 * @return the {@code long} represented by the argument in
479 * decimal.
480 * @throws NumberFormatException if the string does not contain a
481 * parsable {@code long}.
482 */
483 public static long parseLong(String s) throws NumberFormatException {
484 return parseLong(s, 10);
485 }
486
487 /**
488 * Returns a {@code Long} object holding the value
489 * extracted from the specified {@code String} when parsed
490 * with the radix given by the second argument. The first
491 * argument is interpreted as representing a signed
492 * {@code long} in the radix specified by the second
493 * argument, exactly as if the arguments were given to the {@link
494 * #parseLong(java.lang.String, int)} method. The result is a
495 * {@code Long} object that represents the {@code long}
496 * value specified by the string.
497 *
498 * <p>In other words, this method returns a {@code Long} object equal
499 * to the value of:
500 *
501 * <blockquote>
502 * {@code new Long(Long.parseLong(s, radix))}
503 * </blockquote>
504 *
505 * @param s the string to be parsed
506 * @param radix the radix to be used in interpreting {@code s}
507 * @return a {@code Long} object holding the value
960 }
961
962 /**
963 * Compares two {@code long} values numerically.
964 * The value returned is identical to what would be returned by:
965 * <pre>
966 * Long.valueOf(x).compareTo(Long.valueOf(y))
967 * </pre>
968 *
969 * @param x the first {@code long} to compare
970 * @param y the second {@code long} to compare
971 * @return the value {@code 0} if {@code x == y};
972 * a value less than {@code 0} if {@code x < y}; and
973 * a value greater than {@code 0} if {@code x > y}
974 * @since 1.7
975 */
976 public static int compare(long x, long y) {
977 return (x < y) ? -1 : ((x == y) ? 0 : 1);
978 }
979
980
981 // Bit Twiddling
982
983 /**
984 * The number of bits used to represent a {@code long} value in two's
985 * complement binary form.
986 *
987 * @since 1.5
988 */
989 public static final int SIZE = 64;
990
991 /**
992 * Returns a {@code long} value with at most a single one-bit, in the
993 * position of the highest-order ("leftmost") one-bit in the specified
994 * {@code long} value. Returns zero if the specified value has no
995 * one-bits in its two's complement binary representation, that is, if it
996 * is equal to zero.
997 *
998 * @return a {@code long} value with a single one-bit, in the position
999 * of the highest-order one-bit in the specified value, or zero if
|
1 /*
2 * Copyright (c) 1994, 2012, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package java.lang;
27
28 import java.math.*;
29
30 /**
31 * The {@code Long} class wraps a value of the primitive type {@code
32 * long} in an object. An object of type {@code Long} contains a
33 * single field whose type is {@code long}.
34 *
35 * <p> In addition, this class provides several methods for converting
36 * a {@code long} to a {@code String} and a {@code String} to a {@code
37 * long}, as well as other constants and methods useful when dealing
38 * with a {@code long}.
39 *
40 * <p>Implementation note: The implementations of the "bit twiddling"
41 * methods (such as {@link #highestOneBit(long) highestOneBit} and
42 * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are
43 * based on material from Henry S. Warren, Jr.'s <i>Hacker's
44 * Delight</i>, (Addison Wesley, 2002).
45 *
46 * @author Lee Boynton
47 * @author Arthur van Hoff
48 * @author Josh Bloch
49 * @author Joseph D. Darcy
125 boolean negative = (i < 0);
126
127 if (!negative) {
128 i = -i;
129 }
130
131 while (i <= -radix) {
132 buf[charPos--] = Integer.digits[(int)(-(i % radix))];
133 i = i / radix;
134 }
135 buf[charPos] = Integer.digits[(int)(-i)];
136
137 if (negative) {
138 buf[--charPos] = '-';
139 }
140
141 return new String(buf, charPos, (65 - charPos));
142 }
143
144 /**
145 * Returns a string representation of the first argument as an
146 * unsigned integer value in the radix specified by the second
147 * argument.
148 *
149 * <p>If the radix is smaller than {@code Character.MIN_RADIX}
150 * or larger than {@code Character.MAX_RADIX}, then the radix
151 * {@code 10} is used instead.
152 *
153 * <p>Note that since the first argument is treated as an unsigned
154 * value, no leading sign character is printed.
155 *
156 * <p>If the magnitude is zero, it is represented by a single zero
157 * character {@code '0'} (<code>'\u0030'</code>); otherwise,
158 * the first character of the representation of the magnitude will
159 * not be the zero character.
160 *
161 * <p>The behavior of radixes and the characters used as digits
162 * are the same as {@link #toString(long, int) toString}.
163 *
164 * @param i an integer to be converted to an unsigned string.
165 * @param radix the radix to use in the string representation.
166 * @return an unsigned string representation of the argument in the specified radix.
167 * @see #toString(long, int)
168 * @since 1.8
169 */
170 public static String toUnsignedString(long i, int radix) {
171 if (i >= 0)
172 return toString(i, radix);
173 else {
174 switch (radix) {
175 case 2:
176 return toBinaryString(i);
177
178 case 4:
179 return toUnsignedString0(i, 2);
180
181 case 8:
182 return toOctalString(i);
183
184 case 10:
185 /*
186 * We can get the effect of an unsigned division by 10
187 * on a long value by first shifting right, yielding a
188 * positive value, and then dividing by 5. This
189 * allows the last digit and preceding digits to be
190 * isolated more quickly than by an initial conversion
191 * to BigInteger.
192 */
193 long quot = (i >>> 1) / 5;
194 long rem = i - quot * 10;
195 return toString(quot) + rem;
196
197 case 16:
198 return toHexString(i);
199
200 case 32:
201 return toUnsignedString0(i, 5);
202
203 default:
204 return toUnsignedBigInteger(i).toString(radix);
205 }
206 }
207 }
208
209 /**
210 * Return a BigInteger equal to the unsigned value of the
211 * argument.
212 */
213 private static BigInteger toUnsignedBigInteger(long i) {
214 if (i >= 0L)
215 return BigInteger.valueOf(i);
216 else {
217 int upper = (int) (i >>> 32);
218 int lower = (int) i;
219
220 // return (upper << 32) + lower
221 return (BigInteger.valueOf(Integer.toUnsignedLong(upper))).shiftLeft(32).
222 add(BigInteger.valueOf(Integer.toUnsignedLong(lower)));
223 }
224 }
225
226 /**
227 * Returns a string representation of the {@code long}
228 * argument as an unsigned integer in base 16.
229 *
230 * <p>The unsigned {@code long} value is the argument plus
231 * 2<sup>64</sup> if the argument is negative; otherwise, it is
232 * equal to the argument. This value is converted to a string of
233 * ASCII digits in hexadecimal (base 16) with no extra
234 * leading {@code 0}s.
235 *
236 * <p>The value of the argument can be recovered from the returned
237 * string {@code s} by calling {@link
238 * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s,
239 * 16)}.
240 *
241 * <p>If the unsigned magnitude is zero, it is represented by a
242 * single zero character {@code '0'} (<code>'\u0030'</code>);
243 * otherwise, the first character of the representation of the
244 * unsigned magnitude will not be the zero character. The
245 * following characters are used as hexadecimal digits:
246 *
247 * <blockquote>
248 * {@code 0123456789abcdef}
249 * </blockquote>
250 *
251 * These are the characters <code>'\u0030'</code> through
252 * <code>'\u0039'</code> and <code>'\u0061'</code> through
253 * <code>'\u0066'</code>. If uppercase letters are desired,
254 * the {@link java.lang.String#toUpperCase()} method may be called
255 * on the result:
256 *
257 * <blockquote>
258 * {@code Long.toHexString(n).toUpperCase()}
259 * </blockquote>
260 *
261 * @param i a {@code long} to be converted to a string.
262 * @return the string representation of the unsigned {@code long}
263 * value represented by the argument in hexadecimal
264 * (base 16).
265 * @see #parseUnsignedLong(String, int)
266 * @see #toUnsignedString(long, int)
267 * @since JDK 1.0.2
268 */
269 public static String toHexString(long i) {
270 return toUnsignedString0(i, 4);
271 }
272
273 /**
274 * Returns a string representation of the {@code long}
275 * argument as an unsigned integer in base 8.
276 *
277 * <p>The unsigned {@code long} value is the argument plus
278 * 2<sup>64</sup> if the argument is negative; otherwise, it is
279 * equal to the argument. This value is converted to a string of
280 * ASCII digits in octal (base 8) with no extra leading
281 * {@code 0}s.
282 *
283 * <p>The value of the argument can be recovered from the returned
284 * string {@code s} by calling {@link
285 * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s,
286 * 8)}.
287 *
288 * <p>If the unsigned magnitude is zero, it is represented by a
289 * single zero character {@code '0'} (<code>'\u0030'</code>);
290 * otherwise, the first character of the representation of the
291 * unsigned magnitude will not be the zero character. The
292 * following characters are used as octal digits:
293 *
294 * <blockquote>
295 * {@code 01234567}
296 * </blockquote>
297 *
298 * These are the characters <code>'\u0030'</code> through
299 * <code>'\u0037'</code>.
300 *
301 * @param i a {@code long} to be converted to a string.
302 * @return the string representation of the unsigned {@code long}
303 * value represented by the argument in octal (base 8).
304 * @see #parseUnsignedLong(String, int)
305 * @see #toUnsignedString(long, int)
306 * @since JDK 1.0.2
307 */
308 public static String toOctalString(long i) {
309 return toUnsignedString0(i, 3);
310 }
311
312 /**
313 * Returns a string representation of the {@code long}
314 * argument as an unsigned integer in base 2.
315 *
316 * <p>The unsigned {@code long} value is the argument plus
317 * 2<sup>64</sup> if the argument is negative; otherwise, it is
318 * equal to the argument. This value is converted to a string of
319 * ASCII digits in binary (base 2) with no extra leading
320 * {@code 0}s.
321 *
322 * <p>The value of the argument can be recovered from the returned
323 * string {@code s} by calling {@link
324 * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s,
325 * 2)}.
326 *
327 * <p>If the unsigned magnitude is zero, it is represented by a
328 * single zero character {@code '0'} (<code>'\u0030'</code>);
329 * otherwise, the first character of the representation of the
330 * unsigned magnitude will not be the zero character. The
331 * characters {@code '0'} (<code>'\u0030'</code>) and {@code
332 * '1'} (<code>'\u0031'</code>) are used as binary digits.
333 *
334 * @param i a {@code long} to be converted to a string.
335 * @return the string representation of the unsigned {@code long}
336 * value represented by the argument in binary (base 2).
337 * @see #parseUnsignedLong(String, int)
338 * @see #toUnsignedString(long, int)
339 * @since JDK 1.0.2
340 */
341 public static String toBinaryString(long i) {
342 return toUnsignedString0(i, 1);
343 }
344
345 /**
346 * Convert the integer to an unsigned number.
347 */
348 private static String toUnsignedString0(long i, int shift) {
349 char[] buf = new char[64];
350 int charPos = 64;
351 int radix = 1 << shift;
352 long mask = radix - 1;
353 do {
354 buf[--charPos] = Integer.digits[(int)(i & mask)];
355 i >>>= shift;
356 } while (i != 0);
357 return new String(buf, charPos, (64 - charPos));
358 }
359
360 /**
361 * Returns a {@code String} object representing the specified
362 * {@code long}. The argument is converted to signed decimal
363 * representation and returned as a string, exactly as if the
364 * argument and the radix 10 were given as arguments to the {@link
365 * #toString(long, int)} method.
366 *
367 * @param i a {@code long} to be converted.
368 * @return a string representation of the argument in base 10.
369 */
370 public static String toString(long i) {
371 if (i == Long.MIN_VALUE)
372 return "-9223372036854775808";
373 int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
374 char[] buf = new char[size];
375 getChars(i, size, buf);
376 return new String(0, size, buf);
377 }
378
379 /**
380 * Returns a string representation of the argument as an unsigned
381 * decimal value.
382 *
383 * The argument is converted to unsigned decimal representation
384 * and returned as a string exactly as if the argument and radix
385 * 10 were given as arguments to the {@link #toUnsignedString(long,
386 * int)} method.
387 *
388 * @param i an integer to be converted to an unsigned string.
389 * @return an unsigned string representation of the argument.
390 * @see #toUnsignedString(long, int)
391 * @since 1.8
392 */
393 public static String toUnsignedString(long i) {
394 return toUnsignedString(i, 10);
395 }
396
397 /**
398 * Places characters representing the integer i into the
399 * character array buf. The characters are placed into
400 * the buffer backwards starting with the least significant
401 * digit at the specified index (exclusive), and working
402 * backwards from there.
403 *
404 * Will fail if i == Long.MIN_VALUE
405 */
406 static void getChars(long i, int index, char[] buf) {
407 long q;
408 int r;
409 int charPos = index;
410 char sign = 0;
411
412 if (i < 0) {
413 sign = '-';
414 i = -i;
415 }
416
417 // Get 2 digits/iteration using longs until quotient fits into an int
592 * #parseLong(java.lang.String, int)} method.
593 *
594 * <p>Note that neither the character {@code L}
595 * (<code>'\u004C'</code>) nor {@code l}
596 * (<code>'\u006C'</code>) is permitted to appear at the end
597 * of the string as a type indicator, as would be permitted in
598 * Java programming language source code.
599 *
600 * @param s a {@code String} containing the {@code long}
601 * representation to be parsed
602 * @return the {@code long} represented by the argument in
603 * decimal.
604 * @throws NumberFormatException if the string does not contain a
605 * parsable {@code long}.
606 */
607 public static long parseLong(String s) throws NumberFormatException {
608 return parseLong(s, 10);
609 }
610
611 /**
612 * Parses the string argument as an unsigned {@code long} in the
613 * radix specified by the second argument. An unsigned integer
614 * maps the values usually associated with negative numbers to
615 * positive numbers larger than {@code MAX_VALUE}.
616 *
617 * The characters in the string must all be digits of the
618 * specified radix (as determined by whether {@link
619 * java.lang.Character#digit(char, int)} returns a nonnegative
620 * value), except that the first character may be an ASCII plus
621 * sign {@code '+'} (<code>'\u002B'</code>). The resulting
622 * integer value is returned.
623 *
624 * <p>An exception of type {@code NumberFormatException} is
625 * thrown if any of the following situations occurs:
626 * <ul>
627 * <li>The first argument is {@code null} or is a string of
628 * length zero.
629 *
630 * <li>The radix is either smaller than
631 * {@link java.lang.Character#MIN_RADIX} or
632 * larger than {@link java.lang.Character#MAX_RADIX}.
633 *
634 * <li>Any character of the string is not a digit of the specified
635 * radix, except that the first character may be a plus sign
636 * {@code '+'} (<code>'\u002B'</code>) provided that the
637 * string is longer than length 1.
638 *
639 * <li>The value represented by the string is larger than the
640 * largest unsigned {@code long}, 2<sup>64</sup>-1.
641 *
642 * </ul>
643 *
644 *
645 * @param s the {@code String} containing the unsigned integer
646 * representation to be parsed
647 * @param radix the radix to be used while parsing {@code s}.
648 * @return the unsigned {@code long} represented by the string
649 * argument in the specified radix.
650 * @throws NumberFormatException if the {@code String}
651 * does not contain a parsable {@code long}.
652 * @since 1.8
653 */
654 public static long parseUnsignedLong(String s, int radix)
655 throws NumberFormatException {
656 if (s == null) {
657 throw new NumberFormatException("null");
658 }
659
660 int len = s.length();
661 if (len > 0) {
662 char firstChar = s.charAt(0);
663 if (firstChar == '-') {
664 throw new
665 NumberFormatException(String.format("Illegal leading minus sign " +
666 "on unsigned string %s.", s));
667 } else {
668 if (len <= 12 || // Long.MAX_VALUE in Character.MAX_RADIX is 13 digits
669 (radix == 10 && len <= 18) ) { // Long.MAX_VALUE in base 10 is 19 digits
670 return parseLong(s, radix);
671 }
672
673 // No need for range checks on len due to testing above.
674 long first = parseLong(s.substring(0, len - 1), radix);
675 int second = Character.digit(s.charAt(len - 1), radix);
676 if (second < 0) {
677 throw new NumberFormatException("Bad digit at end of " + s);
678 }
679 long result = first * radix + second;
680 if (compareUnsigned(result, first) < 0) {
681 /*
682 * The maximum unsigned value, (2^64)-1, takes at
683 * most one more digit to represent than the
684 * maximum signed value, (2^63)-1. Therefore,
685 * parsing (len - 1) digits will be appropriately
686 * in-range of the signed parsing. In other
687 * words, if parsing (len -1) digits overflows
688 * signed parsing, parsing len digits will
689 * certainly overflow unsigned parsing.
690 *
691 * The compareUnsigned check above catches
692 * situations where an unsigned overflow occurs
693 * incorporating the contribution of the final
694 * digit.
695 */
696 throw new NumberFormatException(String.format("String value %s exceeds " +
697 "range of unsigned long.", s));
698 }
699 return result;
700 }
701 } else {
702 throw NumberFormatException.forInputString(s);
703 }
704 }
705
706 /**
707 * Parses the string argument as an unsigned decimal {@code long}. The
708 * characters in the string must all be decimal digits, except
709 * that the first character may be an an ASCII plus sign {@code
710 * '+'} (<code>'\u002B'</code>). The resulting integer value
711 * is returned, exactly as if the argument and the radix 10 were
712 * given as arguments to the {@link
713 * #parseUnsignedLong(java.lang.String, int)} method.
714 *
715 * @param s a {@code String} containing the unsigned {@code long}
716 * representation to be parsed
717 * @return the unsigned {@code long} value represented by the decimal string argument
718 * @throws NumberFormatException if the string does not contain a
719 * parsable unsigned integer.
720 * @since 1.8
721 */
722 public static long parseUnsignedLong(String s) throws NumberFormatException {
723 return parseUnsignedLong(s, 10);
724 }
725
726 /**
727 * Returns a {@code Long} object holding the value
728 * extracted from the specified {@code String} when parsed
729 * with the radix given by the second argument. The first
730 * argument is interpreted as representing a signed
731 * {@code long} in the radix specified by the second
732 * argument, exactly as if the arguments were given to the {@link
733 * #parseLong(java.lang.String, int)} method. The result is a
734 * {@code Long} object that represents the {@code long}
735 * value specified by the string.
736 *
737 * <p>In other words, this method returns a {@code Long} object equal
738 * to the value of:
739 *
740 * <blockquote>
741 * {@code new Long(Long.parseLong(s, radix))}
742 * </blockquote>
743 *
744 * @param s the string to be parsed
745 * @param radix the radix to be used in interpreting {@code s}
746 * @return a {@code Long} object holding the value
1199 }
1200
1201 /**
1202 * Compares two {@code long} values numerically.
1203 * The value returned is identical to what would be returned by:
1204 * <pre>
1205 * Long.valueOf(x).compareTo(Long.valueOf(y))
1206 * </pre>
1207 *
1208 * @param x the first {@code long} to compare
1209 * @param y the second {@code long} to compare
1210 * @return the value {@code 0} if {@code x == y};
1211 * a value less than {@code 0} if {@code x < y}; and
1212 * a value greater than {@code 0} if {@code x > y}
1213 * @since 1.7
1214 */
1215 public static int compare(long x, long y) {
1216 return (x < y) ? -1 : ((x == y) ? 0 : 1);
1217 }
1218
1219 /**
1220 * Compares two {@code long} values numerically treating the values
1221 * as unsigned.
1222 *
1223 * @param x the first {@code long} to compare
1224 * @param y the second {@code long} to compare
1225 * @return the value {@code 0} if {@code x == y}; a value less
1226 * than {@code 0} if {@code x < y} as unsigned values; and
1227 * a value greater than {@code 0} if {@code x > y} as
1228 * unsigned values
1229 * @since 1.8
1230 */
1231 public static int compareUnsigned(long x, long y) {
1232 return compare(x + MIN_VALUE, y + MIN_VALUE);
1233 }
1234
1235
1236 /**
1237 * Returns the unsigned quotient of dividing the first argument by
1238 * the second where each argument and the result is interpreted as
1239 * an unsigned value.
1240 *
1241 * <p>Note that in two's complement arithmetic, the three other
1242 * basic arithmetic operations of add, subtract, and multiply are
1243 * bit-wise identical if the two operands are regarded as both
1244 * being signed or both being unsigned. Therefore separate {@code
1245 * addUnsigned}, etc. methods are not provided.
1246 *
1247 * @param dividend the value to be divided
1248 * @param divisor the value doing the dividing
1249 * @return the unsigned quotient of the first argument divided by
1250 * the second argument
1251 * @see #remainderUnsigned
1252 * @since 1.8
1253 */
1254 public static long divideUnsigned(long dividend, long divisor) {
1255 if (divisor < 0L) { // signed comparison
1256 // Answer must be 0 or 1 depending on relative magnitude
1257 // of dividend and divisor.
1258 return (compareUnsigned(dividend, divisor)) < 0 ? 0L :1L;
1259 }
1260
1261 if (dividend > 0) // Both inputs non-negative
1262 return dividend/divisor;
1263 else {
1264 /*
1265 * For simple code, leveraging BigInteger. Longer and faster
1266 * code written directly in terms of operations on longs is
1267 * possible; see "Hacker's Delight" for divide and remainder
1268 * algorithms.
1269 */
1270 return toUnsignedBigInteger(dividend).
1271 divide(toUnsignedBigInteger(divisor)).longValue();
1272 }
1273 }
1274
1275 /**
1276 * Returns the unsigned remainder from dividing the first argument
1277 * by the second where each argument and the result is interpreted
1278 * as an unsigned value.
1279 *
1280 * @param dividend the value to be divided
1281 * @param divisor the value doing the dividing
1282 * @return the unsigned remainder of the first argument divided by
1283 * the second argument
1284 * @see #divideUnsigned
1285 * @since 1.8
1286 */
1287 public static long remainderUnsigned(long dividend, long divisor) {
1288 if (dividend > 0 && divisor > 0) { // signed comparisons
1289 return dividend % divisor;
1290 } else {
1291 if (compareUnsigned(dividend, divisor) < 0) // Avoid explicit check for 0 divisor
1292 return dividend;
1293 else
1294 return toUnsignedBigInteger(dividend).
1295 remainder(toUnsignedBigInteger(divisor)).longValue();
1296 }
1297 }
1298
1299 // Bit Twiddling
1300
1301 /**
1302 * The number of bits used to represent a {@code long} value in two's
1303 * complement binary form.
1304 *
1305 * @since 1.5
1306 */
1307 public static final int SIZE = 64;
1308
1309 /**
1310 * Returns a {@code long} value with at most a single one-bit, in the
1311 * position of the highest-order ("leftmost") one-bit in the specified
1312 * {@code long} value. Returns zero if the specified value has no
1313 * one-bits in its two's complement binary representation, that is, if it
1314 * is equal to zero.
1315 *
1316 * @return a {@code long} value with a single one-bit, in the position
1317 * of the highest-order one-bit in the specified value, or zero if
|