1 /*
2 * Copyright (c) 1994, 2025, 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.lang.annotation.Native;
29 import java.lang.invoke.MethodHandles;
30 import java.lang.constant.Constable;
31 import java.lang.constant.ConstantDesc;
32 import java.math.*;
33 import java.util.Objects;
34 import java.util.Optional;
35
36 import jdk.internal.misc.CDS;
37 import jdk.internal.misc.PreviewFeatures;
38 import jdk.internal.value.DeserializeConstructor;
39 import jdk.internal.util.DecimalDigits;
40 import jdk.internal.vm.annotation.ForceInline;
41 import jdk.internal.vm.annotation.IntrinsicCandidate;
42 import jdk.internal.vm.annotation.Stable;
43
44 import static java.lang.Character.digit;
45 import static java.lang.String.COMPACT_STRINGS;
46 import static java.lang.String.LATIN1;
47 import static java.lang.String.UTF16;
48
49 /**
50 * The {@code Long} class is the {@linkplain
51 * java.lang##wrapperClass wrapper class} for values of the primitive
52 * type {@code long}. An object of type {@code Long} contains a
53 * single field whose type is {@code long}.
54 *
55 * <p> In addition, this class provides several methods for converting
56 * a {@code long} to a {@code String} and a {@code String} to a {@code
57 * long}, as well as other constants and methods useful when dealing
58 * with a {@code long}.
59 *
60 * <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
61 * class; programmers should treat instances that are {@linkplain #equals(Object) equal}
62 * as interchangeable and should not use instances for synchronization, mutexes, or
63 * with {@linkplain java.lang.ref.Reference object references}.
64 *
65 * <div class="preview-block">
66 * <div class="preview-comment">
67 * When preview features are enabled, {@code Long} is a {@linkplain Class#isValue value class}.
68 * Use of value class instances for synchronization, mutexes, or with
69 * {@linkplain java.lang.ref.Reference object references} result in
70 * {@link IdentityException}.
71 * </div>
72 * </div>
73 *
74 *
75 * <p>Implementation note: The implementations of the "bit twiddling"
76 * methods (such as {@link #highestOneBit(long) highestOneBit} and
77 * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are
78 * based on material from Henry S. Warren, Jr.'s <cite>Hacker's
79 * Delight</cite>, (Addison Wesley, 2002) and <cite>Hacker's
80 * Delight, Second Edition</cite>, (Pearson Education, 2013).
81 *
82 * @author Lee Boynton
83 * @author Arthur van Hoff
84 * @author Josh Bloch
85 * @author Joseph D. Darcy
86 * @since 1.0
87 */
88 @jdk.internal.MigratedValueClass
89 @jdk.internal.ValueBased
90 public final class Long extends Number
91 implements Comparable<Long>, Constable, ConstantDesc {
92 /**
93 * A constant holding the minimum value a {@code long} can
94 * have, -2<sup>63</sup>.
95 */
96 @Native public static final long MIN_VALUE = 0x8000000000000000L;
97
98 /**
99 * A constant holding the maximum value a {@code long} can
100 * have, 2<sup>63</sup>-1.
101 */
102 @Native public static final long MAX_VALUE = 0x7fffffffffffffffL;
103
104 /**
105 * The {@code Class} instance representing the primitive type
106 * {@code long}.
107 *
108 * @since 1.1
109 */
110 public static final Class<Long> TYPE = Class.getPrimitiveClass("long");
111
112 /**
113 * Returns a string representation of the first argument in the
114 * radix specified by the second argument.
115 *
116 * <p>If the radix is smaller than {@code Character.MIN_RADIX}
117 * or larger than {@code Character.MAX_RADIX}, then the radix
118 * {@code 10} is used instead.
119 *
120 * <p>If the first argument is negative, the first element of the
121 * result is the ASCII minus sign {@code '-'}
122 * ({@code '\u005Cu002d'}). If the first argument is not
123 * negative, no sign character appears in the result.
124 *
125 * <p>The remaining characters of the result represent the magnitude
126 * of the first argument. If the magnitude is zero, it is
127 * represented by a single zero character {@code '0'}
128 * ({@code '\u005Cu0030'}); otherwise, the first character of
129 * the representation of the magnitude will not be the zero
130 * character. The following ASCII characters are used as digits:
131 *
132 * <blockquote>
133 * {@code 0123456789abcdefghijklmnopqrstuvwxyz}
134 * </blockquote>
135 *
136 * These are {@code '\u005Cu0030'} through
137 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through
138 * {@code '\u005Cu007a'}. If {@code radix} is
139 * <var>N</var>, then the first <var>N</var> of these characters
140 * are used as radix-<var>N</var> digits in the order shown. Thus,
141 * the digits for hexadecimal (radix 16) are
142 * {@code 0123456789abcdef}. If uppercase letters are
143 * desired, the {@link java.lang.String#toUpperCase()} method may
144 * be called on the result:
145 *
146 * <blockquote>
147 * {@code Long.toString(n, 16).toUpperCase()}
148 * </blockquote>
149 *
150 * @param i a {@code long} to be converted to a string.
151 * @param radix the radix to use in the string representation.
152 * @return a string representation of the argument in the specified radix.
153 * @see java.lang.Character#MAX_RADIX
154 * @see java.lang.Character#MIN_RADIX
155 */
156 public static String toString(long i, int radix) {
157 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
158 radix = 10;
159 if (radix == 10)
160 return toString(i);
161
162 if (COMPACT_STRINGS) {
163 byte[] buf = new byte[65];
164 int charPos = 64;
165 boolean negative = (i < 0);
166
167 if (!negative) {
168 i = -i;
169 }
170
171 while (i <= -radix) {
172 buf[charPos--] = Integer.digits[(int)(-(i % radix))];
173 i = i / radix;
174 }
175 buf[charPos] = Integer.digits[(int)(-i)];
176
177 if (negative) {
178 buf[--charPos] = '-';
179 }
180 return StringLatin1.newString(buf, charPos, (65 - charPos));
181 }
182 return toStringUTF16(i, radix);
183 }
184
185 private static String toStringUTF16(long i, int radix) {
186 byte[] buf = new byte[65 * 2];
187 int charPos = 64;
188 boolean negative = (i < 0);
189 if (!negative) {
190 i = -i;
191 }
192 while (i <= -radix) {
193 StringUTF16.putChar(buf, charPos--, Integer.digits[(int)(-(i % radix))]);
194 i = i / radix;
195 }
196 StringUTF16.putChar(buf, charPos, Integer.digits[(int)(-i)]);
197 if (negative) {
198 StringUTF16.putChar(buf, --charPos, '-');
199 }
200 return StringUTF16.newString(buf, charPos, (65 - charPos));
201 }
202
203 /**
204 * Returns a string representation of the first argument as an
205 * unsigned integer value in the radix specified by the second
206 * argument.
207 *
208 * <p>If the radix is smaller than {@code Character.MIN_RADIX}
209 * or larger than {@code Character.MAX_RADIX}, then the radix
210 * {@code 10} is used instead.
211 *
212 * <p>Note that since the first argument is treated as an unsigned
213 * value, no leading sign character is printed.
214 *
215 * <p>If the magnitude is zero, it is represented by a single zero
216 * character {@code '0'} ({@code '\u005Cu0030'}); otherwise,
217 * the first character of the representation of the magnitude will
218 * not be the zero character.
219 *
220 * <p>The behavior of radixes and the characters used as digits
221 * are the same as {@link #toString(long, int) toString}.
222 *
223 * @param i an integer to be converted to an unsigned string.
224 * @param radix the radix to use in the string representation.
225 * @return an unsigned string representation of the argument in the specified radix.
226 * @see #toString(long, int)
227 * @since 1.8
228 */
229 public static String toUnsignedString(long i, int radix) {
230 if (i >= 0)
231 return toString(i, radix);
232 else {
233 return switch (radix) {
234 case 2 -> toBinaryString(i);
235 case 4 -> toUnsignedString0(i, 2);
236 case 8 -> toOctalString(i);
237 case 10 -> {
238 /*
239 * We can get the effect of an unsigned division by 10
240 * on a long value by first shifting right, yielding a
241 * positive value, and then dividing by 5. This
242 * allows the last digit and preceding digits to be
243 * isolated more quickly than by an initial conversion
244 * to BigInteger.
245 */
246 long quot = (i >>> 1) / 5;
247 long rem = i - quot * 10;
248 yield toString(quot) + rem;
249 }
250 case 16 -> toHexString(i);
251 case 32 -> toUnsignedString0(i, 5);
252 default -> toUnsignedBigInteger(i).toString(radix);
253 };
254 }
255 }
256
257 /**
258 * Return a BigInteger equal to the unsigned value of the
259 * argument.
260 */
261 private static BigInteger toUnsignedBigInteger(long i) {
262 if (i >= 0L)
263 return BigInteger.valueOf(i);
264 else {
265 int upper = (int) (i >>> 32);
266 int lower = (int) i;
267
268 // return (upper << 32) + lower
269 return (BigInteger.valueOf(Integer.toUnsignedLong(upper))).shiftLeft(32).
270 add(BigInteger.valueOf(Integer.toUnsignedLong(lower)));
271 }
272 }
273
274 /**
275 * Returns a string representation of the {@code long}
276 * argument as an unsigned integer in base 16.
277 *
278 * <p>The unsigned {@code long} value is the argument plus
279 * 2<sup>64</sup> if the argument is negative; otherwise, it is
280 * equal to the argument. This value is converted to a string of
281 * ASCII digits in hexadecimal (base 16) with no extra
282 * leading {@code 0}s.
283 *
284 * <p>The value of the argument can be recovered from the returned
285 * string {@code s} by calling {@link
286 * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s,
287 * 16)}.
288 *
289 * <p>If the unsigned magnitude is zero, it is represented by a
290 * single zero character {@code '0'} ({@code '\u005Cu0030'});
291 * otherwise, the first character of the representation of the
292 * unsigned magnitude will not be the zero character. The
293 * following characters are used as hexadecimal digits:
294 *
295 * <blockquote>
296 * {@code 0123456789abcdef}
297 * </blockquote>
298 *
299 * These are the characters {@code '\u005Cu0030'} through
300 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through
301 * {@code '\u005Cu0066'}. If uppercase letters are desired,
302 * the {@link java.lang.String#toUpperCase()} method may be called
303 * on the result:
304 *
305 * <blockquote>
306 * {@code Long.toHexString(n).toUpperCase()}
307 * </blockquote>
308 *
309 * @apiNote
310 * The {@link java.util.HexFormat} class provides formatting and parsing
311 * of byte arrays and primitives to return a string or adding to an {@link Appendable}.
312 * {@code HexFormat} formats and parses uppercase or lowercase hexadecimal characters,
313 * with leading zeros and for byte arrays includes for each byte
314 * a delimiter, prefix, and suffix.
315 *
316 * @param i a {@code long} to be converted to a string.
317 * @return the string representation of the unsigned {@code long}
318 * value represented by the argument in hexadecimal
319 * (base 16).
320 * @see java.util.HexFormat
321 * @see #parseUnsignedLong(String, int)
322 * @see #toUnsignedString(long, int)
323 * @since 1.0.2
324 */
325 public static String toHexString(long i) {
326 return toUnsignedString0(i, 4);
327 }
328
329 /**
330 * Returns a string representation of the {@code long}
331 * argument as an unsigned integer in base 8.
332 *
333 * <p>The unsigned {@code long} value is the argument plus
334 * 2<sup>64</sup> if the argument is negative; otherwise, it is
335 * equal to the argument. This value is converted to a string of
336 * ASCII digits in octal (base 8) with no extra leading
337 * {@code 0}s.
338 *
339 * <p>The value of the argument can be recovered from the returned
340 * string {@code s} by calling {@link
341 * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s,
342 * 8)}.
343 *
344 * <p>If the unsigned magnitude is zero, it is represented by a
345 * single zero character {@code '0'} ({@code '\u005Cu0030'});
346 * otherwise, the first character of the representation of the
347 * unsigned magnitude will not be the zero character. The
348 * following characters are used as octal digits:
349 *
350 * <blockquote>
351 * {@code 01234567}
352 * </blockquote>
353 *
354 * These are the characters {@code '\u005Cu0030'} through
355 * {@code '\u005Cu0037'}.
356 *
357 * @param i a {@code long} to be converted to a string.
358 * @return the string representation of the unsigned {@code long}
359 * value represented by the argument in octal (base 8).
360 * @see #parseUnsignedLong(String, int)
361 * @see #toUnsignedString(long, int)
362 * @since 1.0.2
363 */
364 public static String toOctalString(long i) {
365 return toUnsignedString0(i, 3);
366 }
367
368 /**
369 * Returns a string representation of the {@code long}
370 * argument as an unsigned integer in base 2.
371 *
372 * <p>The unsigned {@code long} value is the argument plus
373 * 2<sup>64</sup> if the argument is negative; otherwise, it is
374 * equal to the argument. This value is converted to a string of
375 * ASCII digits in binary (base 2) with no extra leading
376 * {@code 0}s.
377 *
378 * <p>The value of the argument can be recovered from the returned
379 * string {@code s} by calling {@link
380 * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s,
381 * 2)}.
382 *
383 * <p>If the unsigned magnitude is zero, it is represented by a
384 * single zero character {@code '0'} ({@code '\u005Cu0030'});
385 * otherwise, the first character of the representation of the
386 * unsigned magnitude will not be the zero character. The
387 * characters {@code '0'} ({@code '\u005Cu0030'}) and {@code
388 * '1'} ({@code '\u005Cu0031'}) are used as binary digits.
389 *
390 * @param i a {@code long} to be converted to a string.
391 * @return the string representation of the unsigned {@code long}
392 * value represented by the argument in binary (base 2).
393 * @see #parseUnsignedLong(String, int)
394 * @see #toUnsignedString(long, int)
395 * @since 1.0.2
396 */
397 public static String toBinaryString(long i) {
398 return toUnsignedString0(i, 1);
399 }
400
401 /**
402 * Format a long (treated as unsigned) into a String.
403 * @param val the value to format
404 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
405 */
406 static String toUnsignedString0(long val, int shift) {
407 // assert shift > 0 && shift <=5 : "Illegal shift value";
408 int mag = Long.SIZE - Long.numberOfLeadingZeros(val);
409 int chars = Math.max(((mag + (shift - 1)) / shift), 1);
410 if (COMPACT_STRINGS) {
411 byte[] buf = new byte[chars];
412 formatUnsignedLong0(val, shift, buf, 0, chars);
413 return new String(buf, LATIN1);
414 } else {
415 byte[] buf = new byte[chars * 2];
416 formatUnsignedLong0UTF16(val, shift, buf, 0, chars);
417 return new String(buf, UTF16);
418 }
419 }
420
421 /**
422 * Format a long (treated as unsigned) into a byte buffer (LATIN1 version). If
423 * {@code len} exceeds the formatted ASCII representation of {@code val},
424 * {@code buf} will be padded with leading zeroes.
425 *
426 * @param val the unsigned long to format
427 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
428 * @param buf the byte buffer to write to
429 * @param offset the offset in the destination buffer to start at
430 * @param len the number of characters to write
431 */
432 private static void formatUnsignedLong0(long val, int shift, byte[] buf, int offset, int len) {
433 int charPos = offset + len;
434 int radix = 1 << shift;
435 int mask = radix - 1;
436 do {
437 buf[--charPos] = Integer.digits[((int) val) & mask];
438 val >>>= shift;
439 } while (charPos > offset);
440 }
441
442 /**
443 * Format a long (treated as unsigned) into a byte buffer (UTF16 version). If
444 * {@code len} exceeds the formatted ASCII representation of {@code val},
445 * {@code buf} will be padded with leading zeroes.
446 *
447 * @param val the unsigned long to format
448 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
449 * @param buf the byte buffer to write to
450 * @param offset the offset in the destination buffer to start at
451 * @param len the number of characters to write
452 */
453 private static void formatUnsignedLong0UTF16(long val, int shift, byte[] buf, int offset, int len) {
454 int charPos = offset + len;
455 int radix = 1 << shift;
456 int mask = radix - 1;
457 do {
458 StringUTF16.putChar(buf, --charPos, Integer.digits[((int) val) & mask]);
459 val >>>= shift;
460 } while (charPos > offset);
461 }
462
463 /**
464 * Returns a {@code String} object representing the specified
465 * {@code long}. The argument is converted to signed decimal
466 * representation and returned as a string, exactly as if the
467 * argument and the radix 10 were given as arguments to the {@link
468 * #toString(long, int)} method.
469 *
470 * @param i a {@code long} to be converted.
471 * @return a string representation of the argument in base 10.
472 */
473 public static String toString(long i) {
474 int size = DecimalDigits.stringSize(i);
475 if (COMPACT_STRINGS) {
476 byte[] buf = new byte[size];
477 DecimalDigits.uncheckedGetCharsLatin1(i, size, buf);
478 return new String(buf, LATIN1);
479 } else {
480 byte[] buf = new byte[size * 2];
481 DecimalDigits.uncheckedGetCharsUTF16(i, size, buf);
482 return new String(buf, UTF16);
483 }
484 }
485
486 /**
487 * Returns a string representation of the argument as an unsigned
488 * decimal value.
489 *
490 * The argument is converted to unsigned decimal representation
491 * and returned as a string exactly as if the argument and radix
492 * 10 were given as arguments to the {@link #toUnsignedString(long,
493 * int)} method.
494 *
495 * @param i an integer to be converted to an unsigned string.
496 * @return an unsigned string representation of the argument.
497 * @see #toUnsignedString(long, int)
498 * @since 1.8
499 */
500 public static String toUnsignedString(long i) {
501 return toUnsignedString(i, 10);
502 }
503
504 /**
505 * Parses the string argument as a signed {@code long} in the
506 * radix specified by the second argument. The characters in the
507 * string must all be digits of the specified radix (as determined
508 * by whether {@link java.lang.Character#digit(char, int)} returns
509 * a nonnegative value), except that the first character may be an
510 * ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to
511 * indicate a negative value or an ASCII plus sign {@code '+'}
512 * ({@code '\u005Cu002B'}) to indicate a positive value. The
513 * resulting {@code long} value is returned.
514 *
515 * <p>Note that neither the character {@code L}
516 * ({@code '\u005Cu004C'}) nor {@code l}
517 * ({@code '\u005Cu006C'}) is permitted to appear at the end
518 * of the string as a type indicator, as would be permitted in
519 * Java programming language source code - except that either
520 * {@code L} or {@code l} may appear as a digit for a
521 * radix greater than or equal to 22.
522 *
523 * <p>An exception of type {@code NumberFormatException} is
524 * thrown if any of the following situations occurs:
525 * <ul>
526 *
527 * <li>The first argument is {@code null} or is a string of
528 * length zero.
529 *
530 * <li>The {@code radix} is either smaller than {@link
531 * java.lang.Character#MIN_RADIX} or larger than {@link
532 * java.lang.Character#MAX_RADIX}.
533 *
534 * <li>Any character of the string is not a digit of the specified
535 * radix, except that the first character may be a minus sign
536 * {@code '-'} ({@code '\u005Cu002d'}) or plus sign {@code
537 * '+'} ({@code '\u005Cu002B'}) provided that the string is
538 * longer than length 1.
539 *
540 * <li>The value represented by the string is not a value of type
541 * {@code long}.
542 * </ul>
543 *
544 * <p>Examples:
545 * <blockquote><pre>
546 * parseLong("0", 10) returns 0L
547 * parseLong("473", 10) returns 473L
548 * parseLong("+42", 10) returns 42L
549 * parseLong("-0", 10) returns 0L
550 * parseLong("-FF", 16) returns -255L
551 * parseLong("1100110", 2) returns 102L
552 * parseLong("99", 8) throws a NumberFormatException
553 * parseLong("Hazelnut", 10) throws a NumberFormatException
554 * parseLong("Hazelnut", 36) returns 1356099454469L
555 * </pre></blockquote>
556 *
557 * @param s the {@code String} containing the
558 * {@code long} representation to be parsed.
559 * @param radix the radix to be used while parsing {@code s}.
560 * @return the {@code long} represented by the string argument in
561 * the specified radix.
562 * @throws NumberFormatException if the string does not contain a
563 * parsable {@code long}.
564 */
565 public static long parseLong(String s, int radix)
566 throws NumberFormatException {
567 if (s == null) {
568 throw new NumberFormatException("Cannot parse null string");
569 }
570
571 if (radix < Character.MIN_RADIX) {
572 throw new NumberFormatException(String.format(
573 "radix %s less than Character.MIN_RADIX", radix));
574 }
575
576 if (radix > Character.MAX_RADIX) {
577 throw new NumberFormatException(String.format(
578 "radix %s greater than Character.MAX_RADIX", radix));
579 }
580
581 int len = s.length();
582 if (len == 0) {
583 throw NumberFormatException.forInputString("", radix);
584 }
585 int digit = ~0xFF;
586 int i = 0;
587 char firstChar = s.charAt(i++);
588 if (firstChar != '-' && firstChar != '+') {
589 digit = digit(firstChar, radix);
590 }
591 if (digit >= 0 || digit == ~0xFF && len > 1) {
592 long limit = firstChar != '-' ? MIN_VALUE + 1 : MIN_VALUE;
593 long multmin = limit / radix;
594 long result = -(digit & 0xFF);
595 boolean inRange = true;
596 /* Accumulating negatively avoids surprises near MAX_VALUE */
597 while (i < len && (digit = digit(s.charAt(i++), radix)) >= 0
598 && (inRange = result > multmin
599 || result == multmin && digit <= (int) (radix * multmin - limit))) {
600 result = radix * result - digit;
601 }
602 if (inRange && i == len && digit >= 0) {
603 return firstChar != '-' ? -result : result;
604 }
605 }
606 throw NumberFormatException.forInputString(s, radix);
607 }
608
609 /**
610 * Parses the {@link CharSequence} argument as a signed {@code long} in
611 * the specified {@code radix}, beginning at the specified
612 * {@code beginIndex} and extending to {@code endIndex - 1}.
613 *
614 * <p>The method does not take steps to guard against the
615 * {@code CharSequence} being mutated while parsing.
616 *
617 * @param s the {@code CharSequence} containing the {@code long}
618 * representation to be parsed
619 * @param beginIndex the beginning index, inclusive.
620 * @param endIndex the ending index, exclusive.
621 * @param radix the radix to be used while parsing {@code s}.
622 * @return the signed {@code long} represented by the subsequence in
623 * the specified radix.
624 * @throws NullPointerException if {@code s} is null.
625 * @throws IndexOutOfBoundsException if {@code beginIndex} is
626 * negative, or if {@code beginIndex} is greater than
627 * {@code endIndex} or if {@code endIndex} is greater than
628 * {@code s.length()}.
629 * @throws NumberFormatException if the {@code CharSequence} does not
630 * contain a parsable {@code long} in the specified
631 * {@code radix}, or if {@code radix} is either smaller than
632 * {@link java.lang.Character#MIN_RADIX} or larger than
633 * {@link java.lang.Character#MAX_RADIX}.
634 * @since 9
635 */
636 public static long parseLong(CharSequence s, int beginIndex, int endIndex, int radix)
637 throws NumberFormatException {
638 Objects.requireNonNull(s);
639 Objects.checkFromToIndex(beginIndex, endIndex, s.length());
640
641 if (radix < Character.MIN_RADIX) {
642 throw new NumberFormatException(String.format(
643 "radix %s less than Character.MIN_RADIX", radix));
644 }
645
646 if (radix > Character.MAX_RADIX) {
647 throw new NumberFormatException(String.format(
648 "radix %s greater than Character.MAX_RADIX", radix));
649 }
650
651 /*
652 * While s can be concurrently modified, it is ensured that each
653 * of its characters is read at most once, from lower to higher indices.
654 * This is obtained by reading them using the pattern s.charAt(i++),
655 * and by not updating i anywhere else.
656 */
657 if (beginIndex == endIndex) {
658 throw NumberFormatException.forInputString("", radix);
659 }
660 int digit = ~0xFF; // ~0xFF means firstChar char is sign
661 int i = beginIndex;
662 char firstChar = s.charAt(i++);
663 if (firstChar != '-' && firstChar != '+') {
664 digit = digit(firstChar, radix);
665 }
666 if (digit >= 0 || digit == ~0xFF && endIndex - beginIndex > 1) {
667 long limit = firstChar != '-' ? MIN_VALUE + 1 : MIN_VALUE;
668 long multmin = limit / radix;
669 long result = -(digit & 0xFF);
670 boolean inRange = true;
671 /* Accumulating negatively avoids surprises near MAX_VALUE */
672 while (i < endIndex && (digit = digit(s.charAt(i++), radix)) >= 0
673 && (inRange = result > multmin
674 || result == multmin && digit <= (int) (radix * multmin - limit))) {
675 result = radix * result - digit;
676 }
677 if (inRange && i == endIndex && digit >= 0) {
678 return firstChar != '-' ? -result : result;
679 }
680 }
681 throw NumberFormatException.forCharSequence(s, beginIndex,
682 endIndex, i - (digit < -1 ? 0 : 1));
683 }
684
685 /**
686 * Parses the string argument as a signed decimal {@code long}.
687 * The characters in the string must all be decimal digits, except
688 * that the first character may be an ASCII minus sign {@code '-'}
689 * ({@code \u005Cu002D'}) to indicate a negative value or an
690 * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
691 * indicate a positive value. The resulting {@code long} value is
692 * returned, exactly as if the argument and the radix {@code 10}
693 * were given as arguments to the {@link
694 * #parseLong(java.lang.String, int)} method.
695 *
696 * <p>Note that neither the character {@code L}
697 * ({@code '\u005Cu004C'}) nor {@code l}
698 * ({@code '\u005Cu006C'}) is permitted to appear at the end
699 * of the string as a type indicator, as would be permitted in
700 * Java programming language source code.
701 *
702 * @param s a {@code String} containing the {@code long}
703 * representation to be parsed
704 * @return the {@code long} represented by the argument in
705 * decimal.
706 * @throws NumberFormatException if the string does not contain a
707 * parsable {@code long}.
708 */
709 public static long parseLong(String s) throws NumberFormatException {
710 return parseLong(s, 10);
711 }
712
713 /**
714 * Parses the string argument as an unsigned {@code long} in the
715 * radix specified by the second argument. An unsigned integer
716 * maps the values usually associated with negative numbers to
717 * positive numbers larger than {@code MAX_VALUE}.
718 *
719 * The characters in the string must all be digits of the
720 * specified radix (as determined by whether {@link
721 * java.lang.Character#digit(char, int)} returns a nonnegative
722 * value), except that the first character may be an ASCII plus
723 * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting
724 * integer value is returned.
725 *
726 * <p>An exception of type {@code NumberFormatException} is
727 * thrown if any of the following situations occurs:
728 * <ul>
729 * <li>The first argument is {@code null} or is a string of
730 * length zero.
731 *
732 * <li>The radix is either smaller than
733 * {@link java.lang.Character#MIN_RADIX} or
734 * larger than {@link java.lang.Character#MAX_RADIX}.
735 *
736 * <li>Any character of the string is not a digit of the specified
737 * radix, except that the first character may be a plus sign
738 * {@code '+'} ({@code '\u005Cu002B'}) provided that the
739 * string is longer than length 1.
740 *
741 * <li>The value represented by the string is larger than the
742 * largest unsigned {@code long}, 2<sup>64</sup>-1.
743 *
744 * </ul>
745 *
746 *
747 * @param s the {@code String} containing the unsigned integer
748 * representation to be parsed
749 * @param radix the radix to be used while parsing {@code s}.
750 * @return the unsigned {@code long} represented by the string
751 * argument in the specified radix.
752 * @throws NumberFormatException if the {@code String}
753 * does not contain a parsable {@code long}.
754 * @since 1.8
755 */
756 public static long parseUnsignedLong(String s, int radix)
757 throws NumberFormatException {
758 if (s == null) {
759 throw new NumberFormatException("Cannot parse null string");
760 }
761
762 if (radix < Character.MIN_RADIX) {
763 throw new NumberFormatException(String.format(
764 "radix %s less than Character.MIN_RADIX", radix));
765 }
766
767 if (radix > Character.MAX_RADIX) {
768 throw new NumberFormatException(String.format(
769 "radix %s greater than Character.MAX_RADIX", radix));
770 }
771
772 int len = s.length();
773 if (len == 0) {
774 throw NumberFormatException.forInputString(s, radix);
775 }
776 int i = 0;
777 char firstChar = s.charAt(i++);
778 if (firstChar == '-') {
779 throw new NumberFormatException(String.format(
780 "Illegal leading minus sign on unsigned string %s.", s));
781 }
782 int digit = ~0xFF;
783 if (firstChar != '+') {
784 digit = digit(firstChar, radix);
785 }
786 if (digit >= 0 || digit == ~0xFF && len > 1) {
787 long multmax = divideUnsigned(-1L, radix); // -1L is max unsigned long
788 long result = digit & 0xFF;
789 boolean inRange = true;
790 while (i < len && (digit = digit(s.charAt(i++), radix)) >= 0
791 && (inRange = compareUnsigned(result, multmax) < 0
792 || result == multmax && digit < (int) (-radix * multmax))) {
793 result = radix * result + digit;
794 }
795 if (inRange && i == len && digit >= 0) {
796 return result;
797 }
798 }
799 if (digit < 0) {
800 throw NumberFormatException.forInputString(s, radix);
801 }
802 throw new NumberFormatException(String.format(
803 "String value %s exceeds range of unsigned long.", s));
804 }
805
806 /**
807 * Parses the {@link CharSequence} argument as an unsigned {@code long} in
808 * the specified {@code radix}, beginning at the specified
809 * {@code beginIndex} and extending to {@code endIndex - 1}.
810 *
811 * <p>The method does not take steps to guard against the
812 * {@code CharSequence} being mutated while parsing.
813 *
814 * @param s the {@code CharSequence} containing the unsigned
815 * {@code long} representation to be parsed
816 * @param beginIndex the beginning index, inclusive.
817 * @param endIndex the ending index, exclusive.
818 * @param radix the radix to be used while parsing {@code s}.
819 * @return the unsigned {@code long} represented by the subsequence in
820 * the specified radix.
821 * @throws NullPointerException if {@code s} is null.
822 * @throws IndexOutOfBoundsException if {@code beginIndex} is
823 * negative, or if {@code beginIndex} is greater than
824 * {@code endIndex} or if {@code endIndex} is greater than
825 * {@code s.length()}.
826 * @throws NumberFormatException if the {@code CharSequence} does not
827 * contain a parsable unsigned {@code long} in the specified
828 * {@code radix}, or if {@code radix} is either smaller than
829 * {@link java.lang.Character#MIN_RADIX} or larger than
830 * {@link java.lang.Character#MAX_RADIX}.
831 * @since 9
832 */
833 public static long parseUnsignedLong(CharSequence s, int beginIndex, int endIndex, int radix)
834 throws NumberFormatException {
835 Objects.requireNonNull(s);
836 Objects.checkFromToIndex(beginIndex, endIndex, s.length());
837
838 if (radix < Character.MIN_RADIX) {
839 throw new NumberFormatException(String.format(
840 "radix %s less than Character.MIN_RADIX", radix));
841 }
842
843 if (radix > Character.MAX_RADIX) {
844 throw new NumberFormatException(String.format(
845 "radix %s greater than Character.MAX_RADIX", radix));
846 }
847
848 /*
849 * While s can be concurrently modified, it is ensured that each
850 * of its characters is read at most once, from lower to higher indices.
851 * This is obtained by reading them using the pattern s.charAt(i++),
852 * and by not updating i anywhere else.
853 */
854 if (beginIndex == endIndex) {
855 throw NumberFormatException.forInputString("", radix);
856 }
857 int i = beginIndex;
858 char firstChar = s.charAt(i++);
859 if (firstChar == '-') {
860 throw new NumberFormatException(
861 "Illegal leading minus sign on unsigned string " + s + ".");
862 }
863 int digit = ~0xFF;
864 if (firstChar != '+') {
865 digit = digit(firstChar, radix);
866 }
867 if (digit >= 0 || digit == ~0xFF && endIndex - beginIndex > 1) {
868 long multmax = divideUnsigned(-1L, radix); // -1L is max unsigned long
869 long result = digit & 0xFF;
870 boolean inRange = true;
871 while (i < endIndex && (digit = digit(s.charAt(i++), radix)) >= 0
872 && (inRange = compareUnsigned(result, multmax) < 0
873 || result == multmax && digit < (int) (-radix * multmax))) {
874 result = radix * result + digit;
875 }
876 if (inRange && i == endIndex && digit >= 0) {
877 return result;
878 }
879 }
880 if (digit < 0) {
881 throw NumberFormatException.forCharSequence(s, beginIndex,
882 endIndex, i - (digit < -1 ? 0 : 1));
883 }
884 throw new NumberFormatException(String.format(
885 "String value %s exceeds range of unsigned long.", s));
886 }
887
888 /**
889 * Parses the string argument as an unsigned decimal {@code long}. The
890 * characters in the string must all be decimal digits, except
891 * that the first character may be an ASCII plus sign {@code
892 * '+'} ({@code '\u005Cu002B'}). The resulting integer value
893 * is returned, exactly as if the argument and the radix 10 were
894 * given as arguments to the {@link
895 * #parseUnsignedLong(java.lang.String, int)} method.
896 *
897 * @param s a {@code String} containing the unsigned {@code long}
898 * representation to be parsed
899 * @return the unsigned {@code long} value represented by the decimal string argument
900 * @throws NumberFormatException if the string does not contain a
901 * parsable unsigned integer.
902 * @since 1.8
903 */
904 public static long parseUnsignedLong(String s) throws NumberFormatException {
905 return parseUnsignedLong(s, 10);
906 }
907
908 /**
909 * Returns a {@code Long} object holding the value
910 * extracted from the specified {@code String} when parsed
911 * with the radix given by the second argument. The first
912 * argument is interpreted as representing a signed
913 * {@code long} in the radix specified by the second
914 * argument, exactly as if the arguments were given to the {@link
915 * #parseLong(java.lang.String, int)} method. The result is a
916 * {@code Long} object that represents the {@code long}
917 * value specified by the string.
918 *
919 * <p>In other words, this method returns a {@code Long} object equal
920 * to the value of:
921 *
922 * <blockquote>
923 * {@code Long.valueOf(Long.parseLong(s, radix))}
924 * </blockquote>
925 *
926 * @param s the string to be parsed
927 * @param radix the radix to be used in interpreting {@code s}
928 * @return a {@code Long} object holding the value
929 * represented by the string argument in the specified
930 * radix.
931 * @throws NumberFormatException If the {@code String} does not
932 * contain a parsable {@code long}.
933 */
934 public static Long valueOf(String s, int radix) throws NumberFormatException {
935 return Long.valueOf(parseLong(s, radix));
936 }
937
938 /**
939 * Returns a {@code Long} object holding the value
940 * of the specified {@code String}. The argument is
941 * interpreted as representing a signed decimal {@code long},
942 * exactly as if the argument were given to the {@link
943 * #parseLong(java.lang.String)} method. The result is a
944 * {@code Long} object that represents the integer value
945 * specified by the string.
946 *
947 * <p>In other words, this method returns a {@code Long} object
948 * equal to the value of:
949 *
950 * <blockquote>
951 * {@code Long.valueOf(Long.parseLong(s))}
952 * </blockquote>
953 *
954 * @param s the string to be parsed.
955 * @return a {@code Long} object holding the value
956 * represented by the string argument.
957 * @throws NumberFormatException If the string cannot be parsed
958 * as a {@code long}.
959 */
960 public static Long valueOf(String s) throws NumberFormatException
961 {
962 return Long.valueOf(parseLong(s, 10));
963 }
964
965 private static final class LongCache {
966 private LongCache() {}
967
968 @Stable
969 static final Long[] cache;
970 static Long[] archivedCache;
971
972 static {
973 int size = -(-128) + 127 + 1;
974
975 // Load and use the archived cache if it exists
976 CDS.initializeFromArchive(LongCache.class);
977 if (archivedCache == null) {
978 Long[] c = new Long[size];
979 long value = -128;
980 for(int i = 0; i < size; i++) {
981 c[i] = new Long(value++);
982 }
983 archivedCache = c;
984 }
985 cache = archivedCache;
986 assert cache.length == size;
987 }
988 }
989
990 /**
991 * Returns a {@code Long} instance representing the specified
992 * {@code long} value.
993 * <div class="preview-block">
994 * <div class="preview-comment">
995 * <p>
996 * - When preview features are NOT enabled, {@code Long} is an identity class.
997 * If a new {@code Long} instance is not required, this method
998 * should generally be used in preference to the constructor
999 * {@link #Long(long)}, as this method is likely to yield
1000 * significantly better space and time performance by caching
1001 * frequently requested values.
1002 * This method will always cache values in the range -128 to 127,
1003 * inclusive, and may cache other values outside of this range.
1004 * </p>
1005 * <p>
1006 * - When preview features are enabled, {@code Long} is a {@linkplain Class#isValue value class}.
1007 * The {@code valueOf} behavior is the same as invoking the constructor,
1008 * whether cached or not.
1009 * </p>
1010 * </div>
1011 * </div>
1012 *
1013 * @param l a long value.
1014 * @return a {@code Long} instance representing {@code l}.
1015 * @since 1.5
1016 */
1017 @IntrinsicCandidate
1018 @DeserializeConstructor
1019 public static Long valueOf(long l) {
1020 if (!PreviewFeatures.isEnabled()) {
1021 if (l >= -128 && l <= 127) { // will cache
1022 final int offset = 128;
1023 return LongCache.cache[(int) l + offset];
1024 }
1025 }
1026 return new Long(l);
1027 }
1028
1029 /**
1030 * Decodes a {@code String} into a {@code Long}.
1031 * Accepts decimal, hexadecimal, and octal numbers given by the
1032 * following grammar:
1033 *
1034 * <blockquote>
1035 * <dl>
1036 * <dt><i>DecodableString:</i>
1037 * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
1038 * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
1039 * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
1040 * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
1041 * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
1042 *
1043 * <dt><i>Sign:</i>
1044 * <dd>{@code -}
1045 * <dd>{@code +}
1046 * </dl>
1047 * </blockquote>
1048 *
1049 * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
1050 * are as defined in section {@jls 3.10.1} of
1051 * <cite>The Java Language Specification</cite>,
1052 * except that underscores are not accepted between digits.
1053 *
1054 * <p>The sequence of characters following an optional
1055 * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
1056 * "{@code #}", or leading zero) is parsed as by the {@code
1057 * Long.parseLong} method with the indicated radix (10, 16, or 8).
1058 * This sequence of characters must represent a positive value or
1059 * a {@link NumberFormatException} will be thrown. The result is
1060 * negated if first character of the specified {@code String} is
1061 * the minus sign. No whitespace characters are permitted in the
1062 * {@code String}.
1063 *
1064 * @param nm the {@code String} to decode.
1065 * @return a {@code Long} object holding the {@code long}
1066 * value represented by {@code nm}
1067 * @throws NumberFormatException if the {@code String} does not
1068 * contain a parsable {@code long}.
1069 * @see java.lang.Long#parseLong(String, int)
1070 * @since 1.2
1071 */
1072 public static Long decode(String nm) throws NumberFormatException {
1073 int radix = 10;
1074 int index = 0;
1075 boolean negative = false;
1076 long result;
1077
1078 if (nm.isEmpty())
1079 throw new NumberFormatException("Zero length string");
1080 char firstChar = nm.charAt(0);
1081 // Handle sign, if present
1082 if (firstChar == '-') {
1083 negative = true;
1084 index++;
1085 } else if (firstChar == '+')
1086 index++;
1087
1088 // Handle radix specifier, if present
1089 if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
1090 index += 2;
1091 radix = 16;
1092 }
1093 else if (nm.startsWith("#", index)) {
1094 index ++;
1095 radix = 16;
1096 }
1097 else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
1098 index ++;
1099 radix = 8;
1100 }
1101
1102 if (nm.startsWith("-", index) || nm.startsWith("+", index))
1103 throw new NumberFormatException("Sign character in wrong position");
1104
1105 try {
1106 result = parseLong(nm, index, nm.length(), radix);
1107 result = negative ? -result : result;
1108 } catch (NumberFormatException e) {
1109 // If number is Long.MIN_VALUE, we'll end up here. The next line
1110 // handles this case, and causes any genuine format error to be
1111 // rethrown.
1112 String constant = negative ? ("-" + nm.substring(index))
1113 : nm.substring(index);
1114 result = parseLong(constant, radix);
1115 }
1116 return result;
1117 }
1118
1119 /**
1120 * The value of the {@code Long}.
1121 *
1122 * @serial
1123 */
1124 private final long value;
1125
1126 /**
1127 * Constructs a newly allocated {@code Long} object that
1128 * represents the specified {@code long} argument.
1129 *
1130 * @param value the value to be represented by the
1131 * {@code Long} object.
1132 *
1133 * @deprecated
1134 * It is rarely appropriate to use this constructor. The static factory
1135 * {@link #valueOf(long)} is generally a better choice, as it is
1136 * likely to yield significantly better space and time performance.
1137 */
1138 @Deprecated(since="9")
1139 public Long(long value) {
1140 this.value = value;
1141 }
1142
1143 /**
1144 * Constructs a newly allocated {@code Long} object that
1145 * represents the {@code long} value indicated by the
1146 * {@code String} parameter. The string is converted to a
1147 * {@code long} value in exactly the manner used by the
1148 * {@code parseLong} method for radix 10.
1149 *
1150 * @param s the {@code String} to be converted to a
1151 * {@code Long}.
1152 * @throws NumberFormatException if the {@code String} does not
1153 * contain a parsable {@code long}.
1154 *
1155 * @deprecated
1156 * It is rarely appropriate to use this constructor.
1157 * Use {@link #parseLong(String)} to convert a string to a
1158 * {@code long} primitive, or use {@link #valueOf(String)}
1159 * to convert a string to a {@code Long} object.
1160 */
1161 @Deprecated(since="9")
1162 public Long(String s) throws NumberFormatException {
1163 this.value = parseLong(s, 10);
1164 }
1165
1166 /**
1167 * Returns the value of this {@code Long} as a {@code byte} after
1168 * a narrowing primitive conversion.
1169 * @jls 5.1.3 Narrowing Primitive Conversion
1170 */
1171 public byte byteValue() {
1172 return (byte)value;
1173 }
1174
1175 /**
1176 * Returns the value of this {@code Long} as a {@code short} after
1177 * a narrowing primitive conversion.
1178 * @jls 5.1.3 Narrowing Primitive Conversion
1179 */
1180 public short shortValue() {
1181 return (short)value;
1182 }
1183
1184 /**
1185 * Returns the value of this {@code Long} as an {@code int} after
1186 * a narrowing primitive conversion.
1187 * @jls 5.1.3 Narrowing Primitive Conversion
1188 */
1189 public int intValue() {
1190 return (int)value;
1191 }
1192
1193 /**
1194 * Returns the value of this {@code Long} as a
1195 * {@code long} value.
1196 */
1197 @IntrinsicCandidate
1198 public long longValue() {
1199 return value;
1200 }
1201
1202 /**
1203 * Returns the value of this {@code Long} as a {@code float} after
1204 * a widening primitive conversion.
1205 * @jls 5.1.2 Widening Primitive Conversion
1206 */
1207 public float floatValue() {
1208 return (float)value;
1209 }
1210
1211 /**
1212 * Returns the value of this {@code Long} as a {@code double}
1213 * after a widening primitive conversion.
1214 * @jls 5.1.2 Widening Primitive Conversion
1215 */
1216 public double doubleValue() {
1217 return (double)value;
1218 }
1219
1220 /**
1221 * Returns a {@code String} object representing this
1222 * {@code Long}'s value. The value is converted to signed
1223 * decimal representation and returned as a string, exactly as if
1224 * the {@code long} value were given as an argument to the
1225 * {@link java.lang.Long#toString(long)} method.
1226 *
1227 * @return a string representation of the value of this object in
1228 * base 10.
1229 */
1230 public String toString() {
1231 return toString(value);
1232 }
1233
1234 /**
1235 * Returns a hash code for this {@code Long}. The result is
1236 * the exclusive OR of the two halves of the primitive
1237 * {@code long} value held by this {@code Long}
1238 * object. That is, the hashcode is the value of the expression:
1239 *
1240 * <blockquote>
1241 * {@code (int)(this.longValue()^(this.longValue()>>>32))}
1242 * </blockquote>
1243 *
1244 * @return a hash code value for this object.
1245 */
1246 @Override
1247 public int hashCode() {
1248 return Long.hashCode(value);
1249 }
1250
1251 /**
1252 * Returns a hash code for a {@code long} value; compatible with
1253 * {@code Long.hashCode()}.
1254 *
1255 * @param value the value to hash
1256 * @return a hash code value for a {@code long} value.
1257 * @since 1.8
1258 */
1259 public static int hashCode(long value) {
1260 return (int)(value ^ (value >>> 32));
1261 }
1262
1263 /**
1264 * Compares this object to the specified object. The result is
1265 * {@code true} if and only if the argument is not
1266 * {@code null} and is a {@code Long} object that
1267 * contains the same {@code long} value as this object.
1268 *
1269 * @param obj the object to compare with.
1270 * @return {@code true} if the objects are the same;
1271 * {@code false} otherwise.
1272 */
1273 public boolean equals(Object obj) {
1274 if (obj instanceof Long ell) {
1275 return value == ell.longValue();
1276 }
1277 return false;
1278 }
1279
1280 /**
1281 * Determines the {@code long} value of the system property
1282 * with the specified name.
1283 *
1284 * <p>The first argument is treated as the name of a system
1285 * property. System properties are accessible through the {@link
1286 * java.lang.System#getProperty(java.lang.String)} method. The
1287 * string value of this property is then interpreted as a {@code
1288 * long} value using the grammar supported by {@link Long#decode decode}
1289 * and a {@code Long} object representing this value is returned.
1290 *
1291 * <p>If there is no property with the specified name, if the
1292 * specified name is empty or {@code null}, or if the property
1293 * does not have the correct numeric format, then {@code null} is
1294 * returned.
1295 *
1296 * <p>In other words, this method returns a {@code Long} object
1297 * equal to the value of:
1298 *
1299 * <blockquote>
1300 * {@code getLong(nm, null)}
1301 * </blockquote>
1302 *
1303 * @param nm property name.
1304 * @return the {@code Long} value of the property.
1305 * @see java.lang.System#getProperty(java.lang.String)
1306 * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
1307 */
1308 public static Long getLong(String nm) {
1309 return getLong(nm, null);
1310 }
1311
1312 /**
1313 * Determines the {@code long} value of the system property
1314 * with the specified name.
1315 *
1316 * <p>The first argument is treated as the name of a system
1317 * property. System properties are accessible through the {@link
1318 * java.lang.System#getProperty(java.lang.String)} method. The
1319 * string value of this property is then interpreted as a {@code
1320 * long} value using the grammar supported by {@link Long#decode decode}
1321 * and a {@code Long} object representing this value is returned.
1322 *
1323 * <p>The second argument is the default value. A {@code Long} object
1324 * that represents the value of the second argument is returned if there
1325 * is no property of the specified name, if the property does not have
1326 * the correct numeric format, or if the specified name is empty or null.
1327 *
1328 * <p>In other words, this method returns a {@code Long} object equal
1329 * to the value of:
1330 *
1331 * <blockquote>
1332 * {@code getLong(nm, Long.valueOf(val))}
1333 * </blockquote>
1334 *
1335 * but in practice it may be implemented in a manner such as:
1336 *
1337 * <blockquote><pre>
1338 * Long result = getLong(nm, null);
1339 * return (result == null) ? Long.valueOf(val) : result;
1340 * </pre></blockquote>
1341 *
1342 * to avoid the unnecessary allocation of a {@code Long} object when
1343 * the default value is not needed.
1344 *
1345 * @param nm property name.
1346 * @param val default value.
1347 * @return the {@code Long} value of the property.
1348 * @see java.lang.System#getProperty(java.lang.String)
1349 * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
1350 */
1351 public static Long getLong(String nm, long val) {
1352 Long result = Long.getLong(nm, null);
1353 return (result == null) ? Long.valueOf(val) : result;
1354 }
1355
1356 /**
1357 * Returns the {@code long} value of the system property with
1358 * the specified name. The first argument is treated as the name
1359 * of a system property. System properties are accessible through
1360 * the {@link java.lang.System#getProperty(java.lang.String)}
1361 * method. The string value of this property is then interpreted
1362 * as a {@code long} value, as per the
1363 * {@link Long#decode decode} method, and a {@code Long} object
1364 * representing this value is returned; in summary:
1365 *
1366 * <ul>
1367 * <li>If the property value begins with the two ASCII characters
1368 * {@code 0x} or the ASCII character {@code #}, not followed by
1369 * a minus sign, then the rest of it is parsed as a hexadecimal integer
1370 * exactly as for the method {@link #valueOf(java.lang.String, int)}
1371 * with radix 16.
1372 * <li>If the property value begins with the ASCII character
1373 * {@code 0} followed by another character, it is parsed as
1374 * an octal integer exactly as by the method {@link
1375 * #valueOf(java.lang.String, int)} with radix 8.
1376 * <li>Otherwise the property value is parsed as a decimal
1377 * integer exactly as by the method
1378 * {@link #valueOf(java.lang.String, int)} with radix 10.
1379 * </ul>
1380 *
1381 * <p>Note that, in every case, neither {@code L}
1382 * ({@code '\u005Cu004C'}) nor {@code l}
1383 * ({@code '\u005Cu006C'}) is permitted to appear at the end
1384 * of the property value as a type indicator, as would be
1385 * permitted in Java programming language source code.
1386 *
1387 * <p>The second argument is the default value. The default value is
1388 * returned if there is no property of the specified name, if the
1389 * property does not have the correct numeric format, or if the
1390 * specified name is empty or {@code null}.
1391 *
1392 * @param nm property name.
1393 * @param val default value.
1394 * @return the {@code Long} value of the property.
1395 * @see System#getProperty(java.lang.String)
1396 * @see System#getProperty(java.lang.String, java.lang.String)
1397 */
1398 public static Long getLong(String nm, Long val) {
1399 String v = nm != null && !nm.isEmpty() ? System.getProperty(nm) : null;
1400 if (v != null) {
1401 try {
1402 return Long.decode(v);
1403 } catch (NumberFormatException e) {
1404 }
1405 }
1406 return val;
1407 }
1408
1409 /**
1410 * Compares two {@code Long} objects numerically.
1411 *
1412 * @param anotherLong the {@code Long} to be compared.
1413 * @return the value {@code 0} if this {@code Long} is
1414 * equal to the argument {@code Long}; a value less than
1415 * {@code 0} if this {@code Long} is numerically less
1416 * than the argument {@code Long}; and a value greater
1417 * than {@code 0} if this {@code Long} is numerically
1418 * greater than the argument {@code Long} (signed
1419 * comparison).
1420 * @since 1.2
1421 */
1422 public int compareTo(Long anotherLong) {
1423 return compare(this.value, anotherLong.value);
1424 }
1425
1426 /**
1427 * Compares two {@code long} values numerically.
1428 * The value returned is identical to what would be returned by:
1429 * <pre>
1430 * Long.valueOf(x).compareTo(Long.valueOf(y))
1431 * </pre>
1432 *
1433 * @param x the first {@code long} to compare
1434 * @param y the second {@code long} to compare
1435 * @return the value {@code 0} if {@code x == y};
1436 * a value less than {@code 0} if {@code x < y}; and
1437 * a value greater than {@code 0} if {@code x > y}
1438 * @since 1.7
1439 */
1440 public static int compare(long x, long y) {
1441 return (x < y) ? -1 : ((x == y) ? 0 : 1);
1442 }
1443
1444 /**
1445 * Compares two {@code long} values numerically treating the values
1446 * as unsigned.
1447 *
1448 * @param x the first {@code long} to compare
1449 * @param y the second {@code long} to compare
1450 * @return the value {@code 0} if {@code x == y}; a value less
1451 * than {@code 0} if {@code x < y} as unsigned values; and
1452 * a value greater than {@code 0} if {@code x > y} as
1453 * unsigned values
1454 * @since 1.8
1455 */
1456 @IntrinsicCandidate
1457 public static int compareUnsigned(long x, long y) {
1458 return compare(x + MIN_VALUE, y + MIN_VALUE);
1459 }
1460
1461
1462 /**
1463 * Returns the unsigned quotient of dividing the first argument by
1464 * the second where each argument and the result is interpreted as
1465 * an unsigned value.
1466 *
1467 * <p>Note that in two's complement arithmetic, the three other
1468 * basic arithmetic operations of add, subtract, and multiply are
1469 * bit-wise identical if the two operands are regarded as both
1470 * being signed or both being unsigned. Therefore separate {@code
1471 * addUnsigned}, etc. methods are not provided.
1472 *
1473 * @param dividend the value to be divided
1474 * @param divisor the value doing the dividing
1475 * @return the unsigned quotient of the first argument divided by
1476 * the second argument
1477 * @see #remainderUnsigned
1478 * @since 1.8
1479 */
1480 @IntrinsicCandidate
1481 public static long divideUnsigned(long dividend, long divisor) {
1482 /* See Hacker's Delight (2nd ed), section 9.3 */
1483 if (divisor >= 0) {
1484 final long q = (dividend >>> 1) / divisor << 1;
1485 final long r = dividend - q * divisor;
1486 return q + ((r | ~(r - divisor)) >>> (Long.SIZE - 1));
1487 }
1488 return (dividend & ~(dividend - divisor)) >>> (Long.SIZE - 1);
1489 }
1490
1491 /**
1492 * Returns the unsigned remainder from dividing the first argument
1493 * by the second where each argument and the result is interpreted
1494 * as an unsigned value.
1495 *
1496 * @param dividend the value to be divided
1497 * @param divisor the value doing the dividing
1498 * @return the unsigned remainder of the first argument divided by
1499 * the second argument
1500 * @see #divideUnsigned
1501 * @since 1.8
1502 */
1503 @IntrinsicCandidate
1504 public static long remainderUnsigned(long dividend, long divisor) {
1505 /* See Hacker's Delight (2nd ed), section 9.3 */
1506 if (divisor >= 0) {
1507 final long q = (dividend >>> 1) / divisor << 1;
1508 final long r = dividend - q * divisor;
1509 /*
1510 * Here, 0 <= r < 2 * divisor
1511 * (1) When 0 <= r < divisor, the remainder is simply r.
1512 * (2) Otherwise the remainder is r - divisor.
1513 *
1514 * In case (1), r - divisor < 0. Applying ~ produces a long with
1515 * sign bit 0, so >> produces 0. The returned value is thus r.
1516 *
1517 * In case (2), a similar reasoning shows that >> produces -1,
1518 * so the returned value is r - divisor.
1519 */
1520 return r - ((~(r - divisor) >> (Long.SIZE - 1)) & divisor);
1521 }
1522 /*
1523 * (1) When dividend >= 0, the remainder is dividend.
1524 * (2) Otherwise
1525 * (2.1) When dividend < divisor, the remainder is dividend.
1526 * (2.2) Otherwise the remainder is dividend - divisor
1527 *
1528 * A reasoning similar to the above shows that the returned value
1529 * is as expected.
1530 */
1531 return dividend - (((dividend & ~(dividend - divisor)) >> (Long.SIZE - 1)) & divisor);
1532 }
1533
1534 // Bit Twiddling
1535
1536 /**
1537 * The number of bits used to represent a {@code long} value in two's
1538 * complement binary form.
1539 *
1540 * @since 1.5
1541 */
1542 @Native public static final int SIZE = 64;
1543
1544 /**
1545 * The number of bytes used to represent a {@code long} value in two's
1546 * complement binary form.
1547 *
1548 * @since 1.8
1549 */
1550 public static final int BYTES = SIZE / Byte.SIZE;
1551
1552 /**
1553 * Returns a {@code long} value with at most a single one-bit, in the
1554 * position of the highest-order ("leftmost") one-bit in the specified
1555 * {@code long} value. Returns zero if the specified value has no
1556 * one-bits in its two's complement binary representation, that is, if it
1557 * is equal to zero.
1558 *
1559 * @param i the value whose highest one bit is to be computed
1560 * @return a {@code long} value with a single one-bit, in the position
1561 * of the highest-order one-bit in the specified value, or zero if
1562 * the specified value is itself equal to zero.
1563 * @since 1.5
1564 */
1565 public static long highestOneBit(long i) {
1566 return i & (MIN_VALUE >>> numberOfLeadingZeros(i));
1567 }
1568
1569 /**
1570 * Returns a {@code long} value with at most a single one-bit, in the
1571 * position of the lowest-order ("rightmost") one-bit in the specified
1572 * {@code long} value. Returns zero if the specified value has no
1573 * one-bits in its two's complement binary representation, that is, if it
1574 * is equal to zero.
1575 *
1576 * @param i the value whose lowest one bit is to be computed
1577 * @return a {@code long} value with a single one-bit, in the position
1578 * of the lowest-order one-bit in the specified value, or zero if
1579 * the specified value is itself equal to zero.
1580 * @since 1.5
1581 */
1582 public static long lowestOneBit(long i) {
1583 // HD, Section 2-1
1584 return i & -i;
1585 }
1586
1587 /**
1588 * Returns the number of zero bits preceding the highest-order
1589 * ("leftmost") one-bit in the two's complement binary representation
1590 * of the specified {@code long} value. Returns 64 if the
1591 * specified value has no one-bits in its two's complement representation,
1592 * in other words if it is equal to zero.
1593 *
1594 * <p>Note that this method is closely related to the logarithm base 2.
1595 * For all positive {@code long} values x:
1596 * <ul>
1597 * <li>floor(log<sub>2</sub>(x)) = {@code 63 - numberOfLeadingZeros(x)}
1598 * <li>ceil(log<sub>2</sub>(x)) = {@code 64 - numberOfLeadingZeros(x - 1)}
1599 * </ul>
1600 *
1601 * @param i the value whose number of leading zeros is to be computed
1602 * @return the number of zero bits preceding the highest-order
1603 * ("leftmost") one-bit in the two's complement binary representation
1604 * of the specified {@code long} value, or 64 if the value
1605 * is equal to zero.
1606 * @since 1.5
1607 */
1608 @IntrinsicCandidate
1609 public static int numberOfLeadingZeros(long i) {
1610 int x = (int)(i >>> 32);
1611 return x == 0 ? 32 + Integer.numberOfLeadingZeros((int)i)
1612 : Integer.numberOfLeadingZeros(x);
1613 }
1614
1615 /**
1616 * Returns the number of zero bits following the lowest-order ("rightmost")
1617 * one-bit in the two's complement binary representation of the specified
1618 * {@code long} value. Returns 64 if the specified value has no
1619 * one-bits in its two's complement representation, in other words if it is
1620 * equal to zero.
1621 *
1622 * @param i the value whose number of trailing zeros is to be computed
1623 * @return the number of zero bits following the lowest-order ("rightmost")
1624 * one-bit in the two's complement binary representation of the
1625 * specified {@code long} value, or 64 if the value is equal
1626 * to zero.
1627 * @since 1.5
1628 */
1629 @IntrinsicCandidate
1630 public static int numberOfTrailingZeros(long i) {
1631 int x = (int)i;
1632 return x == 0 ? 32 + Integer.numberOfTrailingZeros((int)(i >>> 32))
1633 : Integer.numberOfTrailingZeros(x);
1634 }
1635
1636 /**
1637 * Returns the number of one-bits in the two's complement binary
1638 * representation of the specified {@code long} value. This function is
1639 * sometimes referred to as the <i>population count</i>.
1640 *
1641 * @param i the value whose bits are to be counted
1642 * @return the number of one-bits in the two's complement binary
1643 * representation of the specified {@code long} value.
1644 * @since 1.5
1645 */
1646 @IntrinsicCandidate
1647 public static int bitCount(long i) {
1648 // HD, Figure 5-2
1649 i = i - ((i >>> 1) & 0x5555555555555555L);
1650 i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L);
1651 i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL;
1652 i = i + (i >>> 8);
1653 i = i + (i >>> 16);
1654 i = i + (i >>> 32);
1655 return (int)i & 0x7f;
1656 }
1657
1658 /**
1659 * Returns the value obtained by rotating the two's complement binary
1660 * representation of the specified {@code long} value left by the
1661 * specified number of bits. (Bits shifted out of the left hand, or
1662 * high-order, side reenter on the right, or low-order.)
1663 *
1664 * <p>Note that left rotation with a negative distance is equivalent to
1665 * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
1666 * distance)}. Note also that rotation by any multiple of 64 is a
1667 * no-op, so all but the last six bits of the rotation distance can be
1668 * ignored, even if the distance is negative: {@code rotateLeft(val,
1669 * distance) == rotateLeft(val, distance & 0x3F)}.
1670 *
1671 * @param i the value whose bits are to be rotated left
1672 * @param distance the number of bit positions to rotate left
1673 * @return the value obtained by rotating the two's complement binary
1674 * representation of the specified {@code long} value left by the
1675 * specified number of bits.
1676 * @since 1.5
1677 */
1678 public static long rotateLeft(long i, int distance) {
1679 return (i << distance) | (i >>> -distance);
1680 }
1681
1682 /**
1683 * Returns the value obtained by rotating the two's complement binary
1684 * representation of the specified {@code long} value right by the
1685 * specified number of bits. (Bits shifted out of the right hand, or
1686 * low-order, side reenter on the left, or high-order.)
1687 *
1688 * <p>Note that right rotation with a negative distance is equivalent to
1689 * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
1690 * distance)}. Note also that rotation by any multiple of 64 is a
1691 * no-op, so all but the last six bits of the rotation distance can be
1692 * ignored, even if the distance is negative: {@code rotateRight(val,
1693 * distance) == rotateRight(val, distance & 0x3F)}.
1694 *
1695 * @param i the value whose bits are to be rotated right
1696 * @param distance the number of bit positions to rotate right
1697 * @return the value obtained by rotating the two's complement binary
1698 * representation of the specified {@code long} value right by the
1699 * specified number of bits.
1700 * @since 1.5
1701 */
1702 public static long rotateRight(long i, int distance) {
1703 return (i >>> distance) | (i << -distance);
1704 }
1705
1706 /**
1707 * Returns the value obtained by reversing the order of the bits in the
1708 * two's complement binary representation of the specified {@code long}
1709 * value.
1710 *
1711 * @param i the value to be reversed
1712 * @return the value obtained by reversing order of the bits in the
1713 * specified {@code long} value.
1714 * @since 1.5
1715 */
1716 @IntrinsicCandidate
1717 public static long reverse(long i) {
1718 // HD, Figure 7-1
1719 i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L;
1720 i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L;
1721 i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL;
1722
1723 return reverseBytes(i);
1724 }
1725
1726 /**
1727 * Returns the value obtained by compressing the bits of the
1728 * specified {@code long} value, {@code i}, in accordance with
1729 * the specified bit mask.
1730 * <p>
1731 * For each one-bit value {@code mb} of the mask, from least
1732 * significant to most significant, the bit value of {@code i} at
1733 * the same bit location as {@code mb} is assigned to the compressed
1734 * value contiguously starting from the least significant bit location.
1735 * All the upper remaining bits of the compressed value are set
1736 * to zero.
1737 *
1738 * @apiNote
1739 * Consider the simple case of compressing the digits of a hexadecimal
1740 * value:
1741 * {@snippet lang="java" :
1742 * // Compressing drink to food
1743 * compress(0xCAFEBABEL, 0xFF00FFF0L) == 0xCABABL
1744 * }
1745 * Starting from the least significant hexadecimal digit at position 0
1746 * from the right, the mask {@code 0xFF00FFF0} selects hexadecimal digits
1747 * at positions 1, 2, 3, 6 and 7 of {@code 0xCAFEBABE}. The selected digits
1748 * occur in the resulting compressed value contiguously from digit position
1749 * 0 in the same order.
1750 * <p>
1751 * The following identities all return {@code true} and are helpful to
1752 * understand the behaviour of {@code compress}:
1753 * {@snippet lang="java" :
1754 * // Returns 1 if the bit at position n is one
1755 * compress(x, 1L << n) == (x >> n & 1)
1756 *
1757 * // Logical shift right
1758 * compress(x, -1L << n) == x >>> n
1759 *
1760 * // Any bits not covered by the mask are ignored
1761 * compress(x, m) == compress(x & m, m)
1762 *
1763 * // Compressing a value by itself
1764 * compress(m, m) == (m == -1 || m == 0) ? m : (1L << bitCount(m)) - 1
1765 *
1766 * // Expanding then compressing with the same mask
1767 * compress(expand(x, m), m) == x & compress(m, m)
1768 * }
1769 * <p>
1770 * The Sheep And Goats (SAG) operation (see Hacker's Delight, Second Edition, section 7.7)
1771 * can be implemented as follows:
1772 * {@snippet lang="java" :
1773 * long compressLeft(long i, long mask) {
1774 * // This implementation follows the description in Hacker's Delight which
1775 * // is informative. A more optimal implementation is:
1776 * // Long.compress(i, mask) << -Long.bitCount(mask)
1777 * return Long.reverse(
1778 * Long.compress(Long.reverse(i), Long.reverse(mask)));
1779 * }
1780 *
1781 * long sag(long i, long mask) {
1782 * return compressLeft(i, mask) | Long.compress(i, ~mask);
1783 * }
1784 *
1785 * // Separate the sheep from the goats
1786 * sag(0x00000000_CAFEBABEL, 0xFFFFFFFF_FF00FFF0L) == 0x00000000_CABABFEEL
1787 * }
1788 *
1789 * @param i the value whose bits are to be compressed
1790 * @param mask the bit mask
1791 * @return the compressed value
1792 * @see #expand
1793 * @since 19
1794 */
1795 @IntrinsicCandidate
1796 public static long compress(long i, long mask) {
1797 // See Hacker's Delight (2nd ed) section 7.4 Compress, or Generalized Extract
1798
1799 i = i & mask; // Clear irrelevant bits
1800 long maskCount = ~mask << 1; // Count 0's to right
1801
1802 for (int j = 0; j < 6; j++) {
1803 // Parallel prefix
1804 // Mask prefix identifies bits of the mask that have an odd number of 0's to the right
1805 long maskPrefix = parallelSuffix(maskCount);
1806 // Bits to move
1807 long maskMove = maskPrefix & mask;
1808 // Compress mask
1809 mask = (mask ^ maskMove) | (maskMove >>> (1 << j));
1810 // Bits of i to be moved
1811 long t = i & maskMove;
1812 // Compress i
1813 i = (i ^ t) | (t >>> (1 << j));
1814 // Adjust the mask count by identifying bits that have 0 to the right
1815 maskCount = maskCount & ~maskPrefix;
1816 }
1817 return i;
1818 }
1819
1820 /**
1821 * Returns the value obtained by expanding the bits of the
1822 * specified {@code long} value, {@code i}, in accordance with
1823 * the specified bit mask.
1824 * <p>
1825 * For each one-bit value {@code mb} of the mask, from least
1826 * significant to most significant, the next contiguous bit value
1827 * of {@code i} starting at the least significant bit is assigned
1828 * to the expanded value at the same bit location as {@code mb}.
1829 * All other remaining bits of the expanded value are set to zero.
1830 *
1831 * @apiNote
1832 * Consider the simple case of expanding the digits of a hexadecimal
1833 * value:
1834 * {@snippet lang="java" :
1835 * expand(0x0000CABABL, 0xFF00FFF0L) == 0xCA00BAB0L
1836 * }
1837 * Starting from the least significant hexadecimal digit at position 0
1838 * from the right, the mask {@code 0xFF00FFF0} selects the first five
1839 * hexadecimal digits of {@code 0x0000CABAB}. The selected digits occur
1840 * in the resulting expanded value in order at positions 1, 2, 3, 6, and 7.
1841 * <p>
1842 * The following identities all return {@code true} and are helpful to
1843 * understand the behaviour of {@code expand}:
1844 * {@snippet lang="java" :
1845 * // Logically shift right the bit at position 0
1846 * expand(x, 1L << n) == (x & 1) << n
1847 *
1848 * // Logically shift right
1849 * expand(x, -1L << n) == x << n
1850 *
1851 * // Expanding all bits returns the mask
1852 * expand(-1L, m) == m
1853 *
1854 * // Any bits not covered by the mask are ignored
1855 * expand(x, m) == expand(x, m) & m
1856 *
1857 * // Compressing then expanding with the same mask
1858 * expand(compress(x, m), m) == x & m
1859 * }
1860 * <p>
1861 * The select operation for determining the position of the one-bit with
1862 * index {@code n} in a {@code long} value can be implemented as follows:
1863 * {@snippet lang="java" :
1864 * long select(long i, long n) {
1865 * // the one-bit in i (the mask) with index n
1866 * long nthBit = Long.expand(1L << n, i);
1867 * // the bit position of the one-bit with index n
1868 * return Long.numberOfTrailingZeros(nthBit);
1869 * }
1870 *
1871 * // The one-bit with index 0 is at bit position 1
1872 * select(0b10101010_10101010, 0) == 1
1873 * // The one-bit with index 3 is at bit position 7
1874 * select(0b10101010_10101010, 3) == 7
1875 * }
1876 *
1877 * @param i the value whose bits are to be expanded
1878 * @param mask the bit mask
1879 * @return the expanded value
1880 * @see #compress
1881 * @since 19
1882 */
1883 @IntrinsicCandidate
1884 public static long expand(long i, long mask) {
1885 // Save original mask
1886 long originalMask = mask;
1887 // Count 0's to right
1888 long maskCount = ~mask << 1;
1889 long maskPrefix = parallelSuffix(maskCount);
1890 // Bits to move
1891 long maskMove1 = maskPrefix & mask;
1892 // Compress mask
1893 mask = (mask ^ maskMove1) | (maskMove1 >>> (1 << 0));
1894 maskCount = maskCount & ~maskPrefix;
1895
1896 maskPrefix = parallelSuffix(maskCount);
1897 // Bits to move
1898 long maskMove2 = maskPrefix & mask;
1899 // Compress mask
1900 mask = (mask ^ maskMove2) | (maskMove2 >>> (1 << 1));
1901 maskCount = maskCount & ~maskPrefix;
1902
1903 maskPrefix = parallelSuffix(maskCount);
1904 // Bits to move
1905 long maskMove3 = maskPrefix & mask;
1906 // Compress mask
1907 mask = (mask ^ maskMove3) | (maskMove3 >>> (1 << 2));
1908 maskCount = maskCount & ~maskPrefix;
1909
1910 maskPrefix = parallelSuffix(maskCount);
1911 // Bits to move
1912 long maskMove4 = maskPrefix & mask;
1913 // Compress mask
1914 mask = (mask ^ maskMove4) | (maskMove4 >>> (1 << 3));
1915 maskCount = maskCount & ~maskPrefix;
1916
1917 maskPrefix = parallelSuffix(maskCount);
1918 // Bits to move
1919 long maskMove5 = maskPrefix & mask;
1920 // Compress mask
1921 mask = (mask ^ maskMove5) | (maskMove5 >>> (1 << 4));
1922 maskCount = maskCount & ~maskPrefix;
1923
1924 maskPrefix = parallelSuffix(maskCount);
1925 // Bits to move
1926 long maskMove6 = maskPrefix & mask;
1927
1928 long t = i << (1 << 5);
1929 i = (i & ~maskMove6) | (t & maskMove6);
1930 t = i << (1 << 4);
1931 i = (i & ~maskMove5) | (t & maskMove5);
1932 t = i << (1 << 3);
1933 i = (i & ~maskMove4) | (t & maskMove4);
1934 t = i << (1 << 2);
1935 i = (i & ~maskMove3) | (t & maskMove3);
1936 t = i << (1 << 1);
1937 i = (i & ~maskMove2) | (t & maskMove2);
1938 t = i << (1 << 0);
1939 i = (i & ~maskMove1) | (t & maskMove1);
1940
1941 // Clear irrelevant bits
1942 return i & originalMask;
1943 }
1944
1945 @ForceInline
1946 private static long parallelSuffix(long maskCount) {
1947 long maskPrefix = maskCount ^ (maskCount << 1);
1948 maskPrefix = maskPrefix ^ (maskPrefix << 2);
1949 maskPrefix = maskPrefix ^ (maskPrefix << 4);
1950 maskPrefix = maskPrefix ^ (maskPrefix << 8);
1951 maskPrefix = maskPrefix ^ (maskPrefix << 16);
1952 maskPrefix = maskPrefix ^ (maskPrefix << 32);
1953 return maskPrefix;
1954 }
1955
1956 /**
1957 * Returns the signum function of the specified {@code long} value. (The
1958 * return value is -1 if the specified value is negative; 0 if the
1959 * specified value is zero; and 1 if the specified value is positive.)
1960 *
1961 * @param i the value whose signum is to be computed
1962 * @return the signum function of the specified {@code long} value.
1963 * @since 1.5
1964 */
1965 public static int signum(long i) {
1966 // HD, Section 2-7
1967 return (int) ((i >> 63) | (-i >>> 63));
1968 }
1969
1970 /**
1971 * Returns the value obtained by reversing the order of the bytes in the
1972 * two's complement representation of the specified {@code long} value.
1973 *
1974 * @param i the value whose bytes are to be reversed
1975 * @return the value obtained by reversing the bytes in the specified
1976 * {@code long} value.
1977 * @since 1.5
1978 */
1979 @IntrinsicCandidate
1980 public static long reverseBytes(long i) {
1981 i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
1982 return (i << 48) | ((i & 0xffff0000L) << 16) |
1983 ((i >>> 16) & 0xffff0000L) | (i >>> 48);
1984 }
1985
1986 /**
1987 * Adds two {@code long} values together as per the + operator.
1988 *
1989 * @param a the first operand
1990 * @param b the second operand
1991 * @return the sum of {@code a} and {@code b}
1992 * @see java.util.function.BinaryOperator
1993 * @since 1.8
1994 */
1995 public static long sum(long a, long b) {
1996 return a + b;
1997 }
1998
1999 /**
2000 * Returns the greater of two {@code long} values
2001 * as if by calling {@link Math#max(long, long) Math.max}.
2002 *
2003 * @param a the first operand
2004 * @param b the second operand
2005 * @return the greater of {@code a} and {@code b}
2006 * @see java.util.function.BinaryOperator
2007 * @since 1.8
2008 */
2009 public static long max(long a, long b) {
2010 return Math.max(a, b);
2011 }
2012
2013 /**
2014 * Returns the smaller of two {@code long} values
2015 * as if by calling {@link Math#min(long, long) Math.min}.
2016 *
2017 * @param a the first operand
2018 * @param b the second operand
2019 * @return the smaller of {@code a} and {@code b}
2020 * @see java.util.function.BinaryOperator
2021 * @since 1.8
2022 */
2023 public static long min(long a, long b) {
2024 return Math.min(a, b);
2025 }
2026
2027 /**
2028 * Returns an {@link Optional} containing the nominal descriptor for this
2029 * instance, which is the instance itself.
2030 *
2031 * @return an {@link Optional} describing the {@linkplain Long} instance
2032 * @since 12
2033 */
2034 @Override
2035 public Optional<Long> describeConstable() {
2036 return Optional.of(this);
2037 }
2038
2039 /**
2040 * Resolves this instance as a {@link ConstantDesc}, the result of which is
2041 * the instance itself.
2042 *
2043 * @param lookup ignored
2044 * @return the {@linkplain Long} instance
2045 * @since 12
2046 */
2047 @Override
2048 public Long resolveConstantDesc(MethodHandles.Lookup lookup) {
2049 return this;
2050 }
2051
2052 /** use serialVersionUID from JDK 1.0.2 for interoperability */
2053 @java.io.Serial
2054 @Native private static final long serialVersionUID = 4290774380558885855L;
2055 }