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.ForceInline;
39 import jdk.internal.vm.annotation.IntrinsicCandidate;
40 import jdk.internal.vm.annotation.Stable;
41
42 import static java.lang.Character.digit;
43 import static java.lang.String.COMPACT_STRINGS;
44 import static java.lang.String.LATIN1;
45 import static java.lang.String.UTF16;
46
47 /**
48 * The {@code Long} class is the {@linkplain
49 * java.lang##wrapperClass wrapper class} for values of the primitive
50 * type {@code long}. An object of type {@code Long} contains a
51 * single field whose type is {@code long}.
52 *
53 * <p> In addition, this class provides several methods for converting
54 * a {@code long} to a {@code String} and a {@code String} to a {@code
55 * long}, as well as other constants and methods useful when dealing
56 * with a {@code long}.
57 *
58 * <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
59 * class; programmers should treat instances that are
60 * {@linkplain #equals(Object) equal} as interchangeable and should not
61 * use instances for synchronization, or unpredictable behavior may
62 * occur. For example, in a future release, synchronization may fail.
63 *
64 * <p>Implementation note: The implementations of the "bit twiddling"
65 * methods (such as {@link #highestOneBit(long) highestOneBit} and
66 * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are
67 * based on material from Henry S. Warren, Jr.'s <cite>Hacker's
68 * Delight</cite>, (Addison Wesley, 2002) and <cite>Hacker's
69 * Delight, Second Edition</cite>, (Pearson Education, 2013).
70 *
71 * @since 1.0
72 */
73 @jdk.internal.ValueBased
74 public final class Long extends Number
75 implements Comparable<Long>, Constable, ConstantDesc {
76 /**
77 * A constant holding the minimum value a {@code long} can
78 * have, -2<sup>63</sup>.
79 */
80 @Native public static final long MIN_VALUE = 0x8000000000000000L;
81
82 /**
83 * A constant holding the maximum value a {@code long} can
84 * have, 2<sup>63</sup>-1.
85 */
86 @Native public static final long MAX_VALUE = 0x7fffffffffffffffL;
87
88 /**
89 * The {@code Class} instance representing the primitive type
90 * {@code long}.
91 *
92 * @since 1.1
93 */
94 public static final Class<Long> TYPE = Class.getPrimitiveClass("long");
95
96 /**
97 * Returns a string representation of the first argument in the
98 * radix specified by the second argument.
99 *
100 * <p>If the radix is smaller than {@code Character.MIN_RADIX}
101 * or larger than {@code Character.MAX_RADIX}, then the radix
102 * {@code 10} is used instead.
103 *
104 * <p>If the first argument is negative, the first element of the
105 * result is the ASCII minus sign {@code '-'}
106 * ({@code '\u005Cu002d'}). If the first argument is not
107 * negative, no sign character appears in the result.
108 *
109 * <p>The remaining characters of the result represent the magnitude
110 * of the first argument. If the magnitude is zero, it is
111 * represented by a single zero character {@code '0'}
112 * ({@code '\u005Cu0030'}); otherwise, the first character of
113 * the representation of the magnitude will not be the zero
114 * character. The following ASCII characters are used as digits:
115 *
116 * <blockquote>
117 * {@code 0123456789abcdefghijklmnopqrstuvwxyz}
118 * </blockquote>
119 *
120 * These are {@code '\u005Cu0030'} through
121 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through
122 * {@code '\u005Cu007a'}. If {@code radix} is
123 * <var>N</var>, then the first <var>N</var> of these characters
124 * are used as radix-<var>N</var> digits in the order shown. Thus,
125 * the digits for hexadecimal (radix 16) are
126 * {@code 0123456789abcdef}. If uppercase letters are
127 * desired, the {@link java.lang.String#toUpperCase()} method may
128 * be called on the result:
129 *
130 * <blockquote>
131 * {@code Long.toString(n, 16).toUpperCase()}
132 * </blockquote>
133 *
134 * @param i a {@code long} to be converted to a string.
135 * @param radix the radix to use in the string representation.
136 * @return a string representation of the argument in the specified radix.
137 * @see java.lang.Character#MAX_RADIX
138 * @see java.lang.Character#MIN_RADIX
139 */
140 public static String toString(long i, int radix) {
141 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
142 radix = 10;
143 if (radix == 10)
144 return toString(i);
145
146 if (COMPACT_STRINGS) {
147 byte[] buf = new byte[65];
148 int charPos = 64;
149 boolean negative = (i < 0);
150
151 if (!negative) {
152 i = -i;
153 }
154
155 while (i <= -radix) {
156 buf[charPos--] = Integer.digits[(int)(-(i % radix))];
157 i = i / radix;
158 }
159 buf[charPos] = Integer.digits[(int)(-i)];
160
161 if (negative) {
162 buf[--charPos] = '-';
163 }
164 return StringLatin1.newString(buf, charPos, (65 - charPos));
165 }
166 return toStringUTF16(i, radix);
167 }
168
169 private static String toStringUTF16(long i, int radix) {
170 byte[] buf = new byte[65 * 2];
171 int charPos = 64;
172 boolean negative = (i < 0);
173 if (!negative) {
174 i = -i;
175 }
176 while (i <= -radix) {
177 StringUTF16.putChar(buf, charPos--, Integer.digits[(int)(-(i % radix))]);
178 i = i / radix;
179 }
180 StringUTF16.putChar(buf, charPos, Integer.digits[(int)(-i)]);
181 if (negative) {
182 StringUTF16.putChar(buf, --charPos, '-');
183 }
184 return StringUTF16.newString(buf, charPos, (65 - charPos));
185 }
186
187 /**
188 * Returns a string representation of the first argument as an
189 * unsigned integer value in the radix specified by the second
190 * argument.
191 *
192 * <p>If the radix is smaller than {@code Character.MIN_RADIX}
193 * or larger than {@code Character.MAX_RADIX}, then the radix
194 * {@code 10} is used instead.
195 *
196 * <p>Note that since the first argument is treated as an unsigned
197 * value, no leading sign character is printed.
198 *
199 * <p>If the magnitude is zero, it is represented by a single zero
200 * character {@code '0'} ({@code '\u005Cu0030'}); otherwise,
201 * the first character of the representation of the magnitude will
202 * not be the zero character.
203 *
204 * <p>The behavior of radixes and the characters used as digits
205 * are the same as {@link #toString(long, int) toString}.
206 *
207 * @param i an integer to be converted to an unsigned string.
208 * @param radix the radix to use in the string representation.
209 * @return an unsigned string representation of the argument in the specified radix.
210 * @see #toString(long, int)
211 * @since 1.8
212 */
213 public static String toUnsignedString(long i, int radix) {
214 if (i >= 0)
215 return toString(i, radix);
216 else {
217 return switch (radix) {
218 case 2 -> toBinaryString(i);
219 case 4 -> toUnsignedString0(i, 2);
220 case 8 -> toOctalString(i);
221 case 10 -> {
222 /*
223 * We can get the effect of an unsigned division by 10
224 * on a long value by first shifting right, yielding a
225 * positive value, and then dividing by 5. This
226 * allows the last digit and preceding digits to be
227 * isolated more quickly than by an initial conversion
228 * to BigInteger.
229 */
230 long quot = (i >>> 1) / 5;
231 long rem = i - quot * 10;
232 yield toString(quot) + rem;
233 }
234 case 16 -> toHexString(i);
235 case 32 -> toUnsignedString0(i, 5);
236 default -> toUnsignedBigInteger(i).toString(radix);
237 };
238 }
239 }
240
241 /**
242 * Return a BigInteger equal to the unsigned value of the
243 * argument.
244 */
245 private static BigInteger toUnsignedBigInteger(long i) {
246 if (i >= 0L)
247 return BigInteger.valueOf(i);
248 else {
249 int upper = (int) (i >>> 32);
250 int lower = (int) i;
251
252 // return (upper << 32) + lower
253 return (BigInteger.valueOf(Integer.toUnsignedLong(upper))).shiftLeft(32).
254 add(BigInteger.valueOf(Integer.toUnsignedLong(lower)));
255 }
256 }
257
258 /**
259 * Returns a string representation of the {@code long}
260 * argument as an unsigned integer in base 16.
261 *
262 * <p>The unsigned {@code long} value is the argument plus
263 * 2<sup>64</sup> if the argument is negative; otherwise, it is
264 * equal to the argument. This value is converted to a string of
265 * ASCII digits in hexadecimal (base 16) with no extra
266 * leading {@code 0}s.
267 *
268 * <p>The value of the argument can be recovered from the returned
269 * string {@code s} by calling {@link
270 * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s,
271 * 16)}.
272 *
273 * <p>If the unsigned magnitude is zero, it is represented by a
274 * single zero character {@code '0'} ({@code '\u005Cu0030'});
275 * otherwise, the first character of the representation of the
276 * unsigned magnitude will not be the zero character. The
277 * following characters are used as hexadecimal digits:
278 *
279 * <blockquote>
280 * {@code 0123456789abcdef}
281 * </blockquote>
282 *
283 * These are the characters {@code '\u005Cu0030'} through
284 * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through
285 * {@code '\u005Cu0066'}. If uppercase letters are desired,
286 * the {@link java.lang.String#toUpperCase()} method may be called
287 * on the result:
288 *
289 * <blockquote>
290 * {@code Long.toHexString(n).toUpperCase()}
291 * </blockquote>
292 *
293 * @apiNote
294 * The {@link java.util.HexFormat} class provides formatting and parsing
295 * of byte arrays and primitives to return a string or adding to an {@link Appendable}.
296 * {@code HexFormat} formats and parses uppercase or lowercase hexadecimal characters,
297 * with leading zeros and for byte arrays includes for each byte
298 * a delimiter, prefix, and suffix.
299 *
300 * @param i a {@code long} to be converted to a string.
301 * @return the string representation of the unsigned {@code long}
302 * value represented by the argument in hexadecimal
303 * (base 16).
304 * @see java.util.HexFormat
305 * @see #parseUnsignedLong(String, int)
306 * @see #toUnsignedString(long, int)
307 * @since 1.0.2
308 */
309 public static String toHexString(long i) {
310 return toUnsignedString0(i, 4);
311 }
312
313 /**
314 * Returns a string representation of the {@code long}
315 * argument as an unsigned integer in base 8.
316 *
317 * <p>The unsigned {@code long} value is the argument plus
318 * 2<sup>64</sup> if the argument is negative; otherwise, it is
319 * equal to the argument. This value is converted to a string of
320 * ASCII digits in octal (base 8) with no extra leading
321 * {@code 0}s.
322 *
323 * <p>The value of the argument can be recovered from the returned
324 * string {@code s} by calling {@link
325 * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s,
326 * 8)}.
327 *
328 * <p>If the unsigned magnitude is zero, it is represented by a
329 * single zero character {@code '0'} ({@code '\u005Cu0030'});
330 * otherwise, the first character of the representation of the
331 * unsigned magnitude will not be the zero character. The
332 * following characters are used as octal digits:
333 *
334 * <blockquote>
335 * {@code 01234567}
336 * </blockquote>
337 *
338 * These are the characters {@code '\u005Cu0030'} through
339 * {@code '\u005Cu0037'}.
340 *
341 * @param i a {@code long} to be converted to a string.
342 * @return the string representation of the unsigned {@code long}
343 * value represented by the argument in octal (base 8).
344 * @see #parseUnsignedLong(String, int)
345 * @see #toUnsignedString(long, int)
346 * @since 1.0.2
347 */
348 public static String toOctalString(long i) {
349 return toUnsignedString0(i, 3);
350 }
351
352 /**
353 * Returns a string representation of the {@code long}
354 * argument as an unsigned integer in base 2.
355 *
356 * <p>The unsigned {@code long} value is the argument plus
357 * 2<sup>64</sup> if the argument is negative; otherwise, it is
358 * equal to the argument. This value is converted to a string of
359 * ASCII digits in binary (base 2) with no extra leading
360 * {@code 0}s.
361 *
362 * <p>The value of the argument can be recovered from the returned
363 * string {@code s} by calling {@link
364 * Long#parseUnsignedLong(String, int) Long.parseUnsignedLong(s,
365 * 2)}.
366 *
367 * <p>If the unsigned magnitude is zero, it is represented by a
368 * single zero character {@code '0'} ({@code '\u005Cu0030'});
369 * otherwise, the first character of the representation of the
370 * unsigned magnitude will not be the zero character. The
371 * characters {@code '0'} ({@code '\u005Cu0030'}) and {@code
372 * '1'} ({@code '\u005Cu0031'}) are used as binary digits.
373 *
374 * @param i a {@code long} to be converted to a string.
375 * @return the string representation of the unsigned {@code long}
376 * value represented by the argument in binary (base 2).
377 * @see #parseUnsignedLong(String, int)
378 * @see #toUnsignedString(long, int)
379 * @since 1.0.2
380 */
381 public static String toBinaryString(long i) {
382 return toUnsignedString0(i, 1);
383 }
384
385 /**
386 * Format a long (treated as unsigned) into a String.
387 * @param val the value to format
388 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
389 */
390 static String toUnsignedString0(long val, int shift) {
391 // assert shift > 0 && shift <=5 : "Illegal shift value";
392 int mag = Long.SIZE - Long.numberOfLeadingZeros(val);
393 int chars = Math.max(((mag + (shift - 1)) / shift), 1);
394 byte[] buf = new byte[chars];
395 formatUnsignedLong0(val, shift, buf, 0, chars);
396 return String.newStringWithLatin1Bytes(buf);
397 }
398
399 /**
400 * Format a long (treated as unsigned) into a byte buffer (LATIN1 version). If
401 * {@code len} exceeds the formatted ASCII representation of {@code val},
402 * {@code buf} will be padded with leading zeroes.
403 *
404 * @param val the unsigned long to format
405 * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
406 * @param buf the byte buffer to write to
407 * @param offset the offset in the destination buffer to start at
408 * @param len the number of characters to write
409 */
410 private static void formatUnsignedLong0(long val, int shift, byte[] buf, int offset, int len) {
411 int charPos = offset + len;
412 int radix = 1 << shift;
413 int mask = radix - 1;
414 do {
415 buf[--charPos] = Integer.digits[((int) val) & mask];
416 val >>>= shift;
417 } while (charPos > offset);
418 }
419
420 /**
421 * Returns a {@code String} object representing the specified
422 * {@code long}. The argument is converted to signed decimal
423 * representation and returned as a string, exactly as if the
424 * argument and the radix 10 were given as arguments to the {@link
425 * #toString(long, int)} method.
426 *
427 * @param i a {@code long} to be converted.
428 * @return a string representation of the argument in base 10.
429 */
430 public static String toString(long i) {
431 int size = DecimalDigits.stringSize(i);
432 byte[] buf = new byte[size];
433 DecimalDigits.uncheckedGetCharsLatin1(i, size, buf);
434 return String.newStringWithLatin1Bytes(buf);
435 }
436
437 /**
438 * Returns a string representation of the argument as an unsigned
439 * decimal value.
440 *
441 * The argument is converted to unsigned decimal representation
442 * and returned as a string exactly as if the argument and radix
443 * 10 were given as arguments to the {@link #toUnsignedString(long,
444 * int)} method.
445 *
446 * @param i an integer to be converted to an unsigned string.
447 * @return an unsigned string representation of the argument.
448 * @see #toUnsignedString(long, int)
449 * @since 1.8
450 */
451 public static String toUnsignedString(long i) {
452 return toUnsignedString(i, 10);
453 }
454
455 /**
456 * Parses the string argument as a signed {@code long} in the
457 * radix specified by the second argument. The characters in the
458 * string must all be digits of the specified radix (as determined
459 * by whether {@link java.lang.Character#digit(char, int)} returns
460 * a nonnegative value), except that the first character may be an
461 * ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to
462 * indicate a negative value or an ASCII plus sign {@code '+'}
463 * ({@code '\u005Cu002B'}) to indicate a positive value. The
464 * resulting {@code long} value is returned.
465 *
466 * <p>Note that neither the character {@code L}
467 * ({@code '\u005Cu004C'}) nor {@code l}
468 * ({@code '\u005Cu006C'}) is permitted to appear at the end
469 * of the string as a type indicator, as would be permitted in
470 * Java programming language source code - except that either
471 * {@code L} or {@code l} may appear as a digit for a
472 * radix greater than or equal to 22.
473 *
474 * <p>An exception of type {@code NumberFormatException} is
475 * thrown if any of the following situations occurs:
476 * <ul>
477 *
478 * <li>The first argument is {@code null} or is a string of
479 * length zero.
480 *
481 * <li>The {@code radix} is either smaller than {@link
482 * java.lang.Character#MIN_RADIX} or larger than {@link
483 * java.lang.Character#MAX_RADIX}.
484 *
485 * <li>Any character of the string is not a digit of the specified
486 * radix, except that the first character may be a minus sign
487 * {@code '-'} ({@code '\u005Cu002d'}) or plus sign {@code
488 * '+'} ({@code '\u005Cu002B'}) provided that the string is
489 * longer than length 1.
490 *
491 * <li>The value represented by the string is not a value of type
492 * {@code long}.
493 * </ul>
494 *
495 * <p>Examples:
496 * <blockquote><pre>
497 * parseLong("0", 10) returns 0L
498 * parseLong("473", 10) returns 473L
499 * parseLong("+42", 10) returns 42L
500 * parseLong("-0", 10) returns 0L
501 * parseLong("-FF", 16) returns -255L
502 * parseLong("1100110", 2) returns 102L
503 * parseLong("99", 8) throws a NumberFormatException
504 * parseLong("Hazelnut", 10) throws a NumberFormatException
505 * parseLong("Hazelnut", 36) returns 1356099454469L
506 * </pre></blockquote>
507 *
508 * @param s the {@code String} containing the
509 * {@code long} representation to be parsed.
510 * @param radix the radix to be used while parsing {@code s}.
511 * @return the {@code long} represented by the string argument in
512 * the specified radix.
513 * @throws NumberFormatException if the string does not contain a
514 * parsable {@code long}.
515 */
516 public static long parseLong(String s, int radix)
517 throws NumberFormatException {
518 if (s == null) {
519 throw new NumberFormatException("Cannot parse null string");
520 }
521
522 if (radix < Character.MIN_RADIX) {
523 throw new NumberFormatException(String.format(
524 "radix %s less than Character.MIN_RADIX", radix));
525 }
526
527 if (radix > Character.MAX_RADIX) {
528 throw new NumberFormatException(String.format(
529 "radix %s greater than Character.MAX_RADIX", radix));
530 }
531
532 int len = s.length();
533 if (len == 0) {
534 throw NumberFormatException.forInputString("", radix);
535 }
536 int digit = ~0xFF;
537 int i = 0;
538 char firstChar = s.charAt(i++);
539 if (firstChar != '-' && firstChar != '+') {
540 digit = digit(firstChar, radix);
541 }
542 if (digit >= 0 || digit == ~0xFF && len > 1) {
543 long limit = firstChar != '-' ? MIN_VALUE + 1 : MIN_VALUE;
544 long multmin = limit / radix;
545 long result = -(digit & 0xFF);
546 boolean inRange = true;
547 /* Accumulating negatively avoids surprises near MAX_VALUE */
548 while (i < len && (digit = digit(s.charAt(i++), radix)) >= 0
549 && (inRange = result > multmin
550 || result == multmin && digit <= (int) (radix * multmin - limit))) {
551 result = radix * result - digit;
552 }
553 if (inRange && i == len && digit >= 0) {
554 return firstChar != '-' ? -result : result;
555 }
556 }
557 throw NumberFormatException.forInputString(s, radix);
558 }
559
560 /**
561 * Parses the {@link CharSequence} argument as a signed {@code long} in
562 * the specified {@code radix}, beginning at the specified
563 * {@code beginIndex} and extending to {@code endIndex - 1}.
564 *
565 * <p>The method does not take steps to guard against the
566 * {@code CharSequence} being mutated while parsing.
567 *
568 * @param s the {@code CharSequence} containing the {@code long}
569 * representation to be parsed
570 * @param beginIndex the beginning index, inclusive.
571 * @param endIndex the ending index, exclusive.
572 * @param radix the radix to be used while parsing {@code s}.
573 * @return the signed {@code long} represented by the subsequence in
574 * the specified radix.
575 * @throws NullPointerException if {@code s} is null.
576 * @throws IndexOutOfBoundsException if {@code beginIndex} is
577 * negative, or if {@code beginIndex} is greater than
578 * {@code endIndex} or if {@code endIndex} is greater than
579 * {@code s.length()}.
580 * @throws NumberFormatException if the {@code CharSequence} does not
581 * contain a parsable {@code long} in the specified
582 * {@code radix}, or if {@code radix} is either smaller than
583 * {@link java.lang.Character#MIN_RADIX} or larger than
584 * {@link java.lang.Character#MAX_RADIX}.
585 * @since 9
586 */
587 public static long parseLong(CharSequence s, int beginIndex, int endIndex, int radix)
588 throws NumberFormatException {
589 Objects.requireNonNull(s);
590 Objects.checkFromToIndex(beginIndex, endIndex, s.length());
591
592 if (radix < Character.MIN_RADIX) {
593 throw new NumberFormatException(String.format(
594 "radix %s less than Character.MIN_RADIX", radix));
595 }
596
597 if (radix > Character.MAX_RADIX) {
598 throw new NumberFormatException(String.format(
599 "radix %s greater than Character.MAX_RADIX", radix));
600 }
601
602 /*
603 * While s can be concurrently modified, it is ensured that each
604 * of its characters is read at most once, from lower to higher indices.
605 * This is obtained by reading them using the pattern s.charAt(i++),
606 * and by not updating i anywhere else.
607 */
608 if (beginIndex == endIndex) {
609 throw NumberFormatException.forInputString("", radix);
610 }
611 int digit = ~0xFF; // ~0xFF means firstChar char is sign
612 int i = beginIndex;
613 char firstChar = s.charAt(i++);
614 if (firstChar != '-' && firstChar != '+') {
615 digit = digit(firstChar, radix);
616 }
617 if (digit >= 0 || digit == ~0xFF && endIndex - beginIndex > 1) {
618 long limit = firstChar != '-' ? MIN_VALUE + 1 : MIN_VALUE;
619 long multmin = limit / radix;
620 long result = -(digit & 0xFF);
621 boolean inRange = true;
622 /* Accumulating negatively avoids surprises near MAX_VALUE */
623 while (i < endIndex && (digit = digit(s.charAt(i++), radix)) >= 0
624 && (inRange = result > multmin
625 || result == multmin && digit <= (int) (radix * multmin - limit))) {
626 result = radix * result - digit;
627 }
628 if (inRange && i == endIndex && digit >= 0) {
629 return firstChar != '-' ? -result : result;
630 }
631 }
632 throw NumberFormatException.forCharSequence(s, beginIndex,
633 endIndex, i - (digit < -1 ? 0 : 1));
634 }
635
636 /**
637 * Parses the string argument as a signed decimal {@code long}.
638 * The characters in the string must all be decimal digits, except
639 * that the first character may be an ASCII minus sign {@code '-'}
640 * ({@code \u005Cu002D'}) to indicate a negative value or an
641 * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
642 * indicate a positive value. The resulting {@code long} value is
643 * returned, exactly as if the argument and the radix {@code 10}
644 * were given as arguments to the {@link
645 * #parseLong(java.lang.String, int)} method.
646 *
647 * <p>Note that neither the character {@code L}
648 * ({@code '\u005Cu004C'}) nor {@code l}
649 * ({@code '\u005Cu006C'}) is permitted to appear at the end
650 * of the string as a type indicator, as would be permitted in
651 * Java programming language source code.
652 *
653 * @param s a {@code String} containing the {@code long}
654 * representation to be parsed
655 * @return the {@code long} represented by the argument in
656 * decimal.
657 * @throws NumberFormatException if the string does not contain a
658 * parsable {@code long}.
659 */
660 public static long parseLong(String s) throws NumberFormatException {
661 return parseLong(s, 10);
662 }
663
664 /**
665 * Parses the string argument as an unsigned {@code long} in the
666 * radix specified by the second argument. An unsigned integer
667 * maps the values usually associated with negative numbers to
668 * positive numbers larger than {@code MAX_VALUE}.
669 *
670 * The characters in the string must all be digits of the
671 * specified radix (as determined by whether {@link
672 * java.lang.Character#digit(char, int)} returns a nonnegative
673 * value), except that the first character may be an ASCII plus
674 * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting
675 * integer value is returned.
676 *
677 * <p>An exception of type {@code NumberFormatException} is
678 * thrown if any of the following situations occurs:
679 * <ul>
680 * <li>The first argument is {@code null} or is a string of
681 * length zero.
682 *
683 * <li>The radix is either smaller than
684 * {@link java.lang.Character#MIN_RADIX} or
685 * larger than {@link java.lang.Character#MAX_RADIX}.
686 *
687 * <li>Any character of the string is not a digit of the specified
688 * radix, except that the first character may be a plus sign
689 * {@code '+'} ({@code '\u005Cu002B'}) provided that the
690 * string is longer than length 1.
691 *
692 * <li>The value represented by the string is larger than the
693 * largest unsigned {@code long}, 2<sup>64</sup>-1.
694 *
695 * </ul>
696 *
697 *
698 * @param s the {@code String} containing the unsigned integer
699 * representation to be parsed
700 * @param radix the radix to be used while parsing {@code s}.
701 * @return the unsigned {@code long} represented by the string
702 * argument in the specified radix.
703 * @throws NumberFormatException if the {@code String}
704 * does not contain a parsable {@code long}.
705 * @since 1.8
706 */
707 public static long parseUnsignedLong(String s, int radix)
708 throws NumberFormatException {
709 if (s == null) {
710 throw new NumberFormatException("Cannot parse null string");
711 }
712
713 if (radix < Character.MIN_RADIX) {
714 throw new NumberFormatException(String.format(
715 "radix %s less than Character.MIN_RADIX", radix));
716 }
717
718 if (radix > Character.MAX_RADIX) {
719 throw new NumberFormatException(String.format(
720 "radix %s greater than Character.MAX_RADIX", radix));
721 }
722
723 int len = s.length();
724 if (len == 0) {
725 throw NumberFormatException.forInputString(s, radix);
726 }
727 int i = 0;
728 char firstChar = s.charAt(i++);
729 if (firstChar == '-') {
730 throw new NumberFormatException(String.format(
731 "Illegal leading minus sign on unsigned string %s.", s));
732 }
733 int digit = ~0xFF;
734 if (firstChar != '+') {
735 digit = digit(firstChar, radix);
736 }
737 if (digit >= 0 || digit == ~0xFF && len > 1) {
738 long multmax = divideUnsigned(-1L, radix); // -1L is max unsigned long
739 long result = digit & 0xFF;
740 boolean inRange = true;
741 while (i < len && (digit = digit(s.charAt(i++), radix)) >= 0
742 && (inRange = compareUnsigned(result, multmax) < 0
743 || result == multmax && digit < (int) (-radix * multmax))) {
744 result = radix * result + digit;
745 }
746 if (inRange && i == len && digit >= 0) {
747 return result;
748 }
749 }
750 if (digit < 0) {
751 throw NumberFormatException.forInputString(s, radix);
752 }
753 throw new NumberFormatException(String.format(
754 "String value %s exceeds range of unsigned long.", s));
755 }
756
757 /**
758 * Parses the {@link CharSequence} argument as an unsigned {@code long} in
759 * the specified {@code radix}, beginning at the specified
760 * {@code beginIndex} and extending to {@code endIndex - 1}.
761 *
762 * <p>The method does not take steps to guard against the
763 * {@code CharSequence} being mutated while parsing.
764 *
765 * @param s the {@code CharSequence} containing the unsigned
766 * {@code long} representation to be parsed
767 * @param beginIndex the beginning index, inclusive.
768 * @param endIndex the ending index, exclusive.
769 * @param radix the radix to be used while parsing {@code s}.
770 * @return the unsigned {@code long} represented by the subsequence in
771 * the specified radix.
772 * @throws NullPointerException if {@code s} is null.
773 * @throws IndexOutOfBoundsException if {@code beginIndex} is
774 * negative, or if {@code beginIndex} is greater than
775 * {@code endIndex} or if {@code endIndex} is greater than
776 * {@code s.length()}.
777 * @throws NumberFormatException if the {@code CharSequence} does not
778 * contain a parsable unsigned {@code long} in the specified
779 * {@code radix}, or if {@code radix} is either smaller than
780 * {@link java.lang.Character#MIN_RADIX} or larger than
781 * {@link java.lang.Character#MAX_RADIX}.
782 * @since 9
783 */
784 public static long parseUnsignedLong(CharSequence s, int beginIndex, int endIndex, int radix)
785 throws NumberFormatException {
786 Objects.requireNonNull(s);
787 Objects.checkFromToIndex(beginIndex, endIndex, s.length());
788
789 if (radix < Character.MIN_RADIX) {
790 throw new NumberFormatException(String.format(
791 "radix %s less than Character.MIN_RADIX", radix));
792 }
793
794 if (radix > Character.MAX_RADIX) {
795 throw new NumberFormatException(String.format(
796 "radix %s greater than Character.MAX_RADIX", radix));
797 }
798
799 /*
800 * While s can be concurrently modified, it is ensured that each
801 * of its characters is read at most once, from lower to higher indices.
802 * This is obtained by reading them using the pattern s.charAt(i++),
803 * and by not updating i anywhere else.
804 */
805 if (beginIndex == endIndex) {
806 throw NumberFormatException.forInputString("", radix);
807 }
808 int i = beginIndex;
809 char firstChar = s.charAt(i++);
810 if (firstChar == '-') {
811 throw new NumberFormatException(
812 "Illegal leading minus sign on unsigned string " + s + ".");
813 }
814 int digit = ~0xFF;
815 if (firstChar != '+') {
816 digit = digit(firstChar, radix);
817 }
818 if (digit >= 0 || digit == ~0xFF && endIndex - beginIndex > 1) {
819 long multmax = divideUnsigned(-1L, radix); // -1L is max unsigned long
820 long result = digit & 0xFF;
821 boolean inRange = true;
822 while (i < endIndex && (digit = digit(s.charAt(i++), radix)) >= 0
823 && (inRange = compareUnsigned(result, multmax) < 0
824 || result == multmax && digit < (int) (-radix * multmax))) {
825 result = radix * result + digit;
826 }
827 if (inRange && i == endIndex && digit >= 0) {
828 return result;
829 }
830 }
831 if (digit < 0) {
832 throw NumberFormatException.forCharSequence(s, beginIndex,
833 endIndex, i - (digit < -1 ? 0 : 1));
834 }
835 throw new NumberFormatException(String.format(
836 "String value %s exceeds range of unsigned long.", s));
837 }
838
839 /**
840 * Parses the string argument as an unsigned decimal {@code long}. The
841 * characters in the string must all be decimal digits, except
842 * that the first character may be an ASCII plus sign {@code
843 * '+'} ({@code '\u005Cu002B'}). The resulting integer value
844 * is returned, exactly as if the argument and the radix 10 were
845 * given as arguments to the {@link
846 * #parseUnsignedLong(java.lang.String, int)} method.
847 *
848 * @param s a {@code String} containing the unsigned {@code long}
849 * representation to be parsed
850 * @return the unsigned {@code long} value represented by the decimal string argument
851 * @throws NumberFormatException if the string does not contain a
852 * parsable unsigned integer.
853 * @since 1.8
854 */
855 public static long parseUnsignedLong(String s) throws NumberFormatException {
856 return parseUnsignedLong(s, 10);
857 }
858
859 /**
860 * Returns a {@code Long} object holding the value
861 * extracted from the specified {@code String} when parsed
862 * with the radix given by the second argument. The first
863 * argument is interpreted as representing a signed
864 * {@code long} in the radix specified by the second
865 * argument, exactly as if the arguments were given to the {@link
866 * #parseLong(java.lang.String, int)} method. The result is a
867 * {@code Long} object that represents the {@code long}
868 * value specified by the string.
869 *
870 * <p>In other words, this method returns a {@code Long} object equal
871 * to the value of:
872 *
873 * <blockquote>
874 * {@code Long.valueOf(Long.parseLong(s, radix))}
875 * </blockquote>
876 *
877 * @param s the string to be parsed
878 * @param radix the radix to be used in interpreting {@code s}
879 * @return a {@code Long} object holding the value
880 * represented by the string argument in the specified
881 * radix.
882 * @throws NumberFormatException If the {@code String} does not
883 * contain a parsable {@code long}.
884 */
885 public static Long valueOf(String s, int radix) throws NumberFormatException {
886 return Long.valueOf(parseLong(s, radix));
887 }
888
889 /**
890 * Returns a {@code Long} object holding the value
891 * of the specified {@code String}. The argument is
892 * interpreted as representing a signed decimal {@code long},
893 * exactly as if the argument were given to the {@link
894 * #parseLong(java.lang.String)} method. The result is a
895 * {@code Long} object that represents the integer value
896 * specified by the string.
897 *
898 * <p>In other words, this method returns a {@code Long} object
899 * equal to the value of:
900 *
901 * <blockquote>
902 * {@code Long.valueOf(Long.parseLong(s))}
903 * </blockquote>
904 *
905 * @param s the string to be parsed.
906 * @return a {@code Long} object holding the value
907 * represented by the string argument.
908 * @throws NumberFormatException If the string cannot be parsed
909 * as a {@code long}.
910 */
911 public static Long valueOf(String s) throws NumberFormatException
912 {
913 return Long.valueOf(parseLong(s, 10));
914 }
915
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 }