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