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