本文基于JDK1.8学习与分析Long源码。
public final class Long extends Number implements Comparable<Long>
Long
类包含一个对象中原始类型long
的值。 类型为Long
的对象包含一个单一字段,其类型为long
。此外,该类还提供了一些将long
转换为String
和String
转换为long
,以及在处理long
时有用的其他常量和方法。
package java.lang;
import java.lang.annotation.Native;
import java.math.*;
/**
* @author Lee Boynton
* @author Arthur van Hoff
* @author Josh Bloch
* @author Joseph D. Darcy
* @since JDK1.0
*/
public final class Long extends Number implements Comparable<Long> {
/**
* long类型最小值和最大值
*/
@Native public static final long MIN_VALUE = 0x8000000000000000L;
@Native public static final long MAX_VALUE = 0x7fffffffffffffffL;
/**
* 获取包装类对应的Class类对象
*/
@SuppressWarnings("unchecked")
public static final Class<Long> TYPE = (Class<Long>) Class.getPrimitiveClass("long");
/**
* 基于radix将long类型转为字符串
*/
public static String toString(long i, int radix) {
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
radix = 10;
if (radix == 10)
return toString(i);
char[] buf = new char[65];
int charPos = 64;
boolean negative = (i < 0);
if (!negative) {
i = -i;
}
while (i <= -radix) {
buf[charPos--] = Integer.digits[(int)(-(i % radix))];
i = i / radix;
}
buf[charPos] = Integer.digits[(int)(-i)];
if (negative) {
buf[--charPos] = '-';
}
return new String(buf, charPos, (65 - charPos));
}
/**
* 以radix为基数,返回无符号整形数值的字符串表示形式
*/
public static String toUnsignedString(long i, int radix) {
if (i >= 0)
return toString(i, radix);
else {
switch (radix) {
case 2:
return toBinaryString(i);
case 4:
return toUnsignedString0(i, 2);
case 8:
return toOctalString(i);
case 10:
long quot = (i >>> 1) / 5;
long rem = i - quot * 10;
return toString(quot) + rem;
case 16:
return toHexString(i);
case 32:
return toUnsignedString0(i, 5);
default:
return toUnsignedBigInteger(i).toString(radix);
}
}
}
/**
* long类型转为无符号的BigInteger类型
*/
private static BigInteger toUnsignedBigInteger(long i) {
if (i >= 0L)
return BigInteger.valueOf(i);
else {
int upper = (int) (i >>> 32);
int lower = (int) i;
return (BigInteger.valueOf(Integer.toUnsignedLong(upper))).shiftLeft(32).
add(BigInteger.valueOf(Integer.toUnsignedLong(lower)));
}
}
/**
* 返回 long参数的字符串表示形式,作为16位中的无符号整数。
*/
public static String toHexString(long i) {
return toUnsignedString0(i, 4);
}
/**
* 返回 long参数的字符串表示形式,作为基数8中的无符号整数。
*/
public static String toOctalString(long i) {
return toUnsignedString0(i, 3);
}
/**
* 返回 long参数的字符串表示形式为基数2中的无符号整数。
*/
public static String toBinaryString(long i) {
return toUnsignedString0(i, 1);
}
/**
* 无符号long类型转为字符串
*/
static String toUnsignedString0(long val, int shift) {
int mag = Long.SIZE - Long.numberOfLeadingZeros(val);
int chars = Math.max(((mag + (shift - 1)) / shift), 1);
char[] buf = new char[chars];
formatUnsignedLong(val, shift, buf, 0, chars);
return new String(buf, true);
}
/**
* 格式化无符号long类型,并返回int
*/
static int formatUnsignedLong(long val, int shift, char[] buf, int offset, int len) {
int charPos = len;
int radix = 1 << shift;
int mask = radix - 1;
do {
buf[offset + --charPos] = Integer.digits[((int) val) & mask];
val >>>= shift;
} while (val != 0 && charPos > 0);
return charPos;
}
/**
* long类型转为String
*/
public static String toString(long i) {
if (i == Long.MIN_VALUE)
return "-9223372036854775808";
int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
char[] buf = new char[size];
getChars(i, size, buf);
return new String(buf, true);
}
/**
* long类型转为String
*/
public static String toUnsignedString(long i) {
return toUnsignedString(i, 10);
}
static void getChars(long i, int index, char[] buf) {
long q;
int r;
int charPos = index;
char sign = 0;
if (i < 0) {
sign = '-';
i = -i;
}
while (i > Integer.MAX_VALUE) {
q = i / 100;
r = (int)(i - ((q << 6) + (q << 5) + (q << 2)));
i = q;
buf[--charPos] = Integer.DigitOnes[r];
buf[--charPos] = Integer.DigitTens[r];
}
int q2;
int i2 = (int)i;
while (i2 >= 65536) {
q2 = i2 / 100;
r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
i2 = q2;
buf[--charPos] = Integer.DigitOnes[r];
buf[--charPos] = Integer.DigitTens[r];
}
for (;;) {
q2 = (i2 * 52429) >>> (16+3);
r = i2 - ((q2 << 3) + (q2 << 1));
buf[--charPos] = Integer.digits[r];
i2 = q2;
if (i2 == 0) break;
}
if (sign != 0) {
buf[--charPos] = sign;
}
}
static int stringSize(long x) {
long p = 10;
for (int i=1; i<19; i++) {
if (x < p)
return i;
p = 10*p;
}
return 19;
}
/**
* 以radix为基数,将数值型字符串转为long型
*/
public static long parseLong(String s, int radix)
throws NumberFormatException
{
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
long result = 0;
boolean negative = false;
int i = 0, len = s.length();
long limit = -Long.MAX_VALUE;
long multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') {
if (firstChar == '-') {
negative = true;
limit = Long.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1)
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
/**
* 字符串转换为long类型
*/
public static long parseLong(String s) throws NumberFormatException {
return parseLong(s, 10);
}
/**
* 以radix为基数,将字符串转换为无符号long类型
*/
public static long parseUnsignedLong(String s, int radix)
throws NumberFormatException {
if (s == null) {
throw new NumberFormatException("null");
}
int len = s.length();
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar == '-') {
throw new
NumberFormatException(String.format("Illegal leading minus sign " +
"on unsigned string %s.", s));
} else {
if (len <= 12 ||
(radix == 10 && len <= 18) ) {
return parseLong(s, radix);
}
long first = parseLong(s.substring(0, len - 1), radix);
int second = Character.digit(s.charAt(len - 1), radix);
if (second < 0) {
throw new NumberFormatException("Bad digit at end of " + s);
}
long result = first * radix + second;
if (compareUnsigned(result, first) < 0) {
throw new NumberFormatException(String.format("String value %s exceeds " +
"range of unsigned long.", s));
}
return result;
}
} else {
throw NumberFormatException.forInputString(s);
}
}
/**
* 字符串转换为long类型
*/
public static long parseUnsignedLong(String s) throws NumberFormatException {
return parseUnsignedLong(s, 10);
}
/**
* 返回一个 Long对象,该对象保存从指定的String String的值,并用radix为基数进行解析。
*/
public static Long valueOf(String s, int radix) throws NumberFormatException {
return Long.valueOf(parseLong(s, radix));
}
/**
* 数值型字符串转Long类型
*/
public static Long valueOf(String s) throws NumberFormatException
{
return Long.valueOf(parseLong(s, 10));
}
/**
* 静态内部类,缓存-128~127
*/
private static class LongCache {
private LongCache(){}
static final Long cache[] = new Long[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Long(i - 128);
}
}
/**
* 返回一个 Long指定的 long值的 Long实例
*/
public static Long valueOf(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) {
return LongCache.cache[(int)l + offset];
}
return new Long(l);
}
/**
* 将 String解码为 Long
*/
public static Long decode(String nm) throws NumberFormatException {
int radix = 10;
int index = 0;
boolean negative = false;
Long result;
if (nm.isEmpty())
throw new NumberFormatException("Zero length string");
char firstChar = nm.charAt(0);
if (firstChar == '-') {
negative = true;
index++;
} else if (firstChar == '+')
index++;
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
index += 2;
radix = 16;
}
else if (nm.startsWith("#", index)) {
index ++;
radix = 16;
}
else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
index ++;
radix = 8;
}
if (nm.startsWith("-", index) || nm.startsWith("+", index))
throw new NumberFormatException("Sign character in wrong position");
try {
result = Long.valueOf(nm.substring(index), radix);
result = negative ? Long.valueOf(-result.longValue()) : result;
} catch (NumberFormatException e) {
String constant = negative ? ("-" + nm.substring(index))
: nm.substring(index);
result = Long.valueOf(constant, radix);
}
return result;
}
private final long value;
/**
* 有参构造方法
*/
public Long(long value) {
this.value = value;
}
/**
* 有参构造方法
*/
public Long(String s) throws NumberFormatException {
this.value = parseLong(s, 10);
}
/**
* 返回Long的byte类型
*/
public byte byteValue() {
return (byte)value;
}
/**
* 返回Long的short类型
*/
public short shortValue() {
return (short)value;
}
/**
* 返回Long的int类型
*/
public int intValue() {
return (int)value;
}
/**
* 返回Long的long类型
*/
public long longValue() {
return value;
}
/**
* 返回Long的float类型
*/
public float floatValue() {
return (float)value;
}
/**
* 返回Long的double类型
*/
public double doubleValue() {
return (double)value;
}
/**
* Long类型转为String
*/
public String toString() {
return toString(value);
}
/**
* 返回此Long的哈希码
*/
@Override
public int hashCode() {
return Long.hashCode(value);
}
/**
* 返回给定long类型的哈希码
*/
public static int hashCode(long value) {
return (int)(value ^ (value >>> 32));
}
/**
* 将此对象与指定的对象进行比较
*/
public boolean equals(Object obj) {
if (obj instanceof Long) {
return value == ((Long)obj).longValue();
}
return false;
}
/**
* String转Long类型
*/
public static Long getLong(String nm) {
return getLong(nm, null);
}
/**
* String转Long类型,如果为空返回参数值
*/
public static Long getLong(String nm, long val) {
Long result = Long.getLong(nm, null);
return (result == null) ? Long.valueOf(val) : result;
}
/**
* String类型转Long
*/
public static Long getLong(String nm, Long val) {
String v = null;
try {
v = System.getProperty(nm);
} catch (IllegalArgumentException | NullPointerException e) {
}
if (v != null) {
try {
return Long.decode(v);
} catch (NumberFormatException e) {
}
}
return val;
}
/**
* 数字比较两个 Long对象
*/
public int compareTo(Long anotherLong) {
return compare(this.value, anotherLong.value);
}
/**
* 数值比较两个long数值
*/
public static int compare(long x, long y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
/**
* 将两个 long值进行比较,数值将值视为无符号
*/
public static int compareUnsigned(long x, long y) {
return compare(x + MIN_VALUE, y + MIN_VALUE);
}
/**
* 返回将第一个参数除以秒的无符号商,其中每个参数和结果被解释为无符号值
*/
public static long divideUnsigned(long dividend, long divisor) {
if (divisor < 0L) {
return (compareUnsigned(dividend, divisor)) < 0 ? 0L :1L;
}
if (dividend > 0)
return dividend/divisor;
else {
return toUnsignedBigInteger(dividend).
divide(toUnsignedBigInteger(divisor)).longValue();
}
}
/**
* 返回无符号余数,将第一个参数除以秒,其中每个参数和结果被解释为无符号值
*/
public static long remainderUnsigned(long dividend, long divisor) {
if (dividend > 0 && divisor > 0) {
return dividend % divisor;
} else {
if (compareUnsigned(dividend, divisor) < 0)
return dividend;
else
return toUnsignedBigInteger(dividend).
remainder(toUnsignedBigInteger(divisor)).longValue();
}
}
/**
* 用于表示二进制补码二进制形式的 long值的位数
*/
@Native public static final int SIZE = 64;
/**
* 用于表示二进制补码二进制形式的 long值的字节数
*/
public static final int BYTES = SIZE / Byte.SIZE;
/**
* 返回一个 long值至多一个单个1位,在最高阶(“最左侧”)的位置在指定的一个位 long值
*/
public static long highestOneBit(long i) {
i |= (i >> 1);
i |= (i >> 2);
i |= (i >> 4);
i |= (i >> 8);
i |= (i >> 16);
i |= (i >> 32);
return i - (i >>> 1);
}
/**
* 返回一个 long值至多一个单个1位,在最低阶(“最右边的”)的位置在指定的一个位 long值
*/
public static long lowestOneBit(long i) {
return i & -i;
}
/**
* 返回的最高阶的(“最左边的”)中所指定的二进制补码表示的一个位前述零个比特的数量 long值
*/
public static int numberOfLeadingZeros(long i) {
if (i == 0)
return 64;
int n = 1;
int x = (int)(i >>> 32);
if (x == 0) { n += 32; x = (int)i; }
if (x >>> 16 == 0) { n += 16; x <<= 16; }
if (x >>> 24 == 0) { n += 8; x <<= 8; }
if (x >>> 28 == 0) { n += 4; x <<= 4; }
if (x >>> 30 == 0) { n += 2; x <<= 2; }
n -= x >>> 31;
return n;
}
/**
* 返回零位以下最低阶(“最右边的”)的数量在指定的二进制补码表示的一个位 long值
*/
public static int numberOfTrailingZeros(long i) {
int x, y;
if (i == 0) return 64;
int n = 63;
y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32);
y = x <<16; if (y != 0) { n = n -16; x = y; }
y = x << 8; if (y != 0) { n = n - 8; x = y; }
y = x << 4; if (y != 0) { n = n - 4; x = y; }
y = x << 2; if (y != 0) { n = n - 2; x = y; }
return n - ((x << 1) >>> 31);
}
/**
* 返回指定的long值的二进制补码二进制表示中的long数。 此功能有时称为人口数量
*/
public static int bitCount(long i) {
i = i - ((i >>> 1) & 0x5555555555555555L);
i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L);
i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL;
i = i + (i >>> 8);
i = i + (i >>> 16);
i = i + (i >>> 32);
return (int)i & 0x7f;
}
/**
* 返回通过旋转指定的位数剩下的指定 long值的二进制补码二进制表示获得的值
*/
public static long rotateLeft(long i, int distance) {
return (i << distance) | (i >>> -distance);
}
/**
* 返回通过旋转指定的二的补码的二进制表示而得到的值 long右移位的指定数值
*/
public static long rotateRight(long i, int distance) {
return (i >>> distance) | (i << -distance);
}
/**
* 返回由指定的二进制补码表示反转位的顺序而获得的值 long值
*/
public static long reverse(long i) {
i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L;
i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L;
i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL;
i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
i = (i << 48) | ((i & 0xffff0000L) << 16) |
((i >>> 16) & 0xffff0000L) | (i >>> 48);
return i;
}
/**
* 返回指定值为long的signum函数
*/
public static int signum(long i) {
return (int) ((i >> 63) | (-i >>> 63));
}
/**
* 返回反转指定的二进制补码表示的字节顺序而获得的值 long值
*/
public static long reverseBytes(long i) {
i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
return (i << 48) | ((i & 0xffff0000L) << 16) |
((i >>> 16) & 0xffff0000L) | (i >>> 48);
}
/**
* 两个long类型相加
*/
public static long sum(long a, long b) {
return a + b;
}
/**
* 获得两个long类型的最大值
*/
public static long max(long a, long b) {
return Math.max(a, b);
}
/**
* 获得两个long类型的最小值
*/
public static long min(long a, long b) {
return Math.min(a, b);
}
@Native private static final long serialVersionUID = 4290774380558885855L;
}