Long的源码,基本跟Integer类类似,所以这里贴出源码,直接注释进行理解。
本章内容转载自Java源码解析,Long,如果需要查看详解请参考本人的学习笔记java.lang.Integer进行对比学习.
public class Long extends Number implements Comparable {
/**
* 最小值,-2的63次方
*/
@Native
public static final long MIN_VALUE = 0x8000000000000000L;
/**
* 最大值,2的63次方减1
*/
@Native
public static final long MAX_VALUE = 0x7fffffffffffffffL;
/**
* 返回long的class类型
*/
@SuppressWarnings("unchecked")
public static final Class TYPE = (Class) Class.getPrimitiveClass("long");
/**
* 以指定基数返回指定数的表示形式,传入的可以使十六进制,8进制,10进制
* 返回的可以使3进制、5进制最小2进制,最大36进制
*/
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));
}
/**
* 根据基数返回无符号的二进制形式,这里将正数和负数分开处理
* 是因为负数的二进制其实就是正数的反码加一,所以要不同处理
*/
public static String toUnsignedString(long i, int radix) {
if (i >= 0)
// 大于0的直接toString,而Integer的toUnsignedString,就是先转换成了无符号的int,也会走这里
return toString(i, radix);
else {
// 小于0的要根据不同情况进行处理
switch (radix) {
case 2:
return toBinaryString(i);
case 4:
return toUnsignedString0(i, 2);
case 8:
return toOctalString(i);
case 10:
/*
* We can get the effect of an unsigned division by 10
* on a long value by first shifting right, yielding a
* positive value, and then dividing by 5. This
* allows the last digit and preceding digits to be
* isolated more quickly than by an initial conversion
* to BigInteger.
*/
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);
}
}
}
/**
* 返回指定值的BitInteger的无符号表示形式
* .
*/
private static BigInteger toUnsignedBigInteger(long i) {
if (i >= 0L)
return BigInteger.valueOf(i);
else {
int upper = (int) (i >>> 32);
int lower = (int) i;
// return (upper << 32) + lower
return (BigInteger.valueOf(Integer.toUnsignedLong(upper))).shiftLeft(32).
add(BigInteger.valueOf(Integer.toUnsignedLong(lower)));
}
}
/**
* 返回16进制表示形式,入参可以使8,16,10进制
*/
public static String toHexString(long i) {
return toUnsignedString0(i, 4);
}
/**
* 返回八进制表示形式,入参可以使8,16,10进制
*/
public static String toOctalString(long i) {
return toUnsignedString0(i, 3);
}
/**
* 返回二进制表示形式,入参可以使8,16,10进制
*/
public static String toBinaryString(long i) {
return toUnsignedString0(i, 1);
}
/**
* 将long(这里会将long当做无符号的long处理)转成字符串
*/
static String toUnsignedString0(long val, int shift) {
// assert shift > 0 && shift <=5 : "Illegal shift value";
// 计算val实际占用的bit
int mag = Long.SIZE - Long.numberOfLeadingZeros(val);
// 计算需要打印的字符串的长度
int chars = Math.max(((mag + (shift - 1)) / shift), 1);
char[] buf = new char[chars];
// 填充buf
formatUnsignedLong(val, shift, buf, 0, chars);
return new String(buf, true);
}
/**
* 将指定数的字符串表示形式填充到char数组
*/
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;
}
/**
* 返回指定数的十进制字符串
*
*/
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];
// 填充char数组
getChars(i, size, buf);
return new String(buf, true);
}
/**
* 返回指定数的十进制的无符号的字符串形式
*/
public static String toUnsignedString(long i) {
return toUnsignedString(i, 10);
}
/**
* 这里只用于十进制的数填充到char[]数组中
*/
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;
}
// 大于Integer的最大值时
// 这里主是需要进行一个强转
while (i > Integer.MAX_VALUE) {
q = i / 100;
// really: r = i - (q * 100);
r = (int) (i - ((q << 6) + (q << 5) + (q << 2)));
i = q;
buf[--charPos] = Integer.DigitOnes[r];
buf[--charPos] = Integer.DigitTens[r];
}
// 这下面就和Integer的处理一样了
int q2;
int i2 = (int) i;
while (i2 >= 65536) {
q2 = i2 / 100;
// really: r = i2 - (q * 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)); // r = i2-(q2*10) ...
buf[--charPos] = Integer.digits[r];
i2 = q2;
if (i2 == 0) break;
}
if (sign != 0) {
buf[--charPos] = sign;
}
}
/**
* 计算正整数的位数
* @param x
* @return
*/
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;
}
/**
* 根据基数,返回字符串代表的数字的十进制形式
* 示例:
*
* parseLong("0", 10) returns 0L
* parseLong("473", 10) returns 473L
* parseLong("+42", 10) returns 42L
* parseLong("-0", 10) returns 0L
* parseLong("-FF", 16) returns -255L
* parseLong("1100110", 2) returns 102L
* parseLong("99", 8) throws a NumberFormatException
* parseLong("Hazelnut", 10) throws a NumberFormatException
* parseLong("Hazelnut", 36) returns 1356099454469L
*
*/
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) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
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);
}
/**
* 与toUnsignedString对应,根据基数将无符号的字符串表示的数还原为十进制
*/
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 {
// Long.MAX_VALUE在基数为36时,str的长度是13
// 在基数为10时,str的长度为19
if (len <= 12 ||
(radix == 10 && len <= 18)) {
return parseLong(s, radix);
}
// No need for range checks on len due to testing above.
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;
// 这里就是溢出了long能表示的最大无符号数
if (compareUnsigned(result, first) < 0) {
/*
* 最大无符号值(2 ^ 64)-1最多需要一个数字来表示最大有符号值(2 ^ 63)-1。
* 因此,解析(len-1)数字将适当地在签名解析的范围内。
* 所以,如果解析(len -1)数字溢出了签名解析,解析len数字肯定会溢出无符号解析。
* 上面的compareUnsigned检查捕获了包含最终数字贡献的无符号溢出的情况。
*/
throw new NumberFormatException(String.format("String value %s exceeds " +
"range of unsigned long.", s));
}
return result;
}
} else {
throw NumberFormatException.forInputString(s);
}
}
/**
* 与toUnsignedString对应,根据基数10将无符号的字符串表示的数还原为十进制
*/
public static long parseUnsignedLong(String s) throws NumberFormatException {
return parseUnsignedLong(s, 10);
}
/**
* 根据指定基数,返回字符串的十进制的Long对象
*/
public static Long valueOf(String s, int radix) throws NumberFormatException {
return Long.valueOf(parseLong(s, radix));
}
/**
* 基数为10,返回字符串的十进制的Long对象
*/
public static Long valueOf(String s) throws NumberFormatException {
return Long.valueOf(parseLong(s, 10));
}
/**
* Long的缓存,缓存-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);
}
}
/**
* 自动装箱
*/
public static Long valueOf(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) { // will cache
return Long.LongCache.cache[(int) l + offset];
}
return new Long(l);
}
/**
* 解码字符串,返回一个Long
* 可带-、+号
* 可接受十进制、16进制、8进制
* #、0x和0X开头代表16进制
* 0开头代表8进制
*
*
*
* - DecodableString:
*
- Signopt DecimalNumeral
*
- Signopt {@code 0x} HexDigits
*
- Signopt {@code 0X} HexDigits
*
- Signopt {@code #} HexDigits
*
- Signopt {@code 0} OctalDigits
*/
public static Long decode(String nm) throws NumberFormatException {
int radix = 10;
int index = 0;
boolean negative = false;
Long result;
if (nm.length() == 0)
throw new NumberFormatException("Zero length string");
char firstChar = nm.charAt(0);
// Handle sign, if present
if (firstChar == '-') {
negative = true;
index++;
} else if (firstChar == '+')
index++;
// Handle radix specifier, if present
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) {
// If number is Long.MIN_VALUE, we'll end up here. The next line
// handles this case, and causes any genuine format error to be
// rethrown.
String constant = negative ? ("-" + nm.substring(index))
: nm.substring(index);
result = Long.valueOf(constant, radix);
}
return result;
}
/**
* 实际存储的long
*
* @serial
*/
private final long value;
/**
* 实例化
*/
public Long(long value) {
this.value = value;
}
/**
* 根据字符串实例化,这个字符串会以十进制解析
*/
public Long(String s) throws NumberFormatException {
this.value = parseLong(s, 10);
}
/**
* 缩窄到byte,如果value超出了byte的范围,那么会返回截取后的数,不会报错的
*/
public byte byteValue() {
return (byte) value;
}
/**
* 缩窄到short,如果value超出了short的范围,那么会返回截取后的数,不会报错的
*/
public short shortValue() {
return (short) value;
}
/**
* 缩窄到int,如果value超出了int的范围,那么会返回截取后的数,不会报错的
*/
public int intValue() {
return (int) value;
}
/**
* 返回long
*/
public long longValue() {
return value;
}
/**
* 向上转型
*/
public float floatValue() {
return (float) value;
}
/**
* 向上转型
*/
public double doubleValue() {
return (double) value;
}
/**
* toString
*/
public String toString() {
return toString(value);
}
/**
* hashCode
*/
@Override
public int hashCode() {
return Long.hashCode(value);
}
/**
* hashCode,静态
*/
public static int hashCode(long value) {
return (int) (value ^ (value >>> 32));
}
/**
* equals
*/
public boolean equals(Object obj) {
if (obj instanceof Long) {
return value == ((Long) obj).longValue();
}
return false;
}
/**
* 根据系统属性名返回对应的Long对象
*/
public static Long getLong(String nm) {
return getLong(nm, null);
}
/**
* 根据系统属性名返回对应的Long对象,可以给默认值
*/
public static Long getLong(String nm, long val) {
Long result = Long.getLong(nm, null);
return (result == null) ? Long.valueOf(val) : result;
}
/**
* 根据系统属性名返回对应的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;
}
/**
* compareTo
*/
public int compareTo(Long anotherLong) {
return compare(this.value, anotherLong.value);
}
/**
* 比较两个数
*/
public static int compare(long x, long y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
/**
* 比较两个数,以无符号方式
*/
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) { // signed comparison
// Answer must be 0 or 1 depending on relative magnitude
// of dividend and divisor.
return (compareUnsigned(dividend, divisor)) < 0 ? 0L : 1L;
}
if (dividend > 0) // Both inputs non-negative
return dividend / divisor;
else {
/*
* For simple code, leveraging BigInteger. Longer and faster
* code written directly in terms of operations on longs is
* possible; see "Hacker's Delight" for divide and remainder
* algorithms.
*/
return toUnsignedBigInteger(dividend).
divide(toUnsignedBigInteger(divisor)).longValue();
}
}
/**
* 用第一个参数除以第二个参数求余数,以无符号的方式,并且返回的结果也是个无符号数
*/
public static long remainderUnsigned(long dividend, long divisor) {
if (dividend > 0 && divisor > 0) { // signed comparisons
return dividend % divisor;
} else {
if (compareUnsigned(dividend, divisor) < 0) // Avoid explicit check for 0 divisor
return dividend;
else
return toUnsignedBigInteger(dividend).
remainder(toUnsignedBigInteger(divisor)).longValue();
}
}
// Bit Twiddling
/**
* long占的bit位数
*/
@Native
public static final int SIZE = 64;
/**
* long站的byte位数
*/
public static final int BYTES = SIZE / Byte.SIZE;
/**
* 二进制最高位1的权值,
* 如5的二进制101,最低位的1在最低位,权值为4
* 10的二进制1010,最低位的1在倒数第二位,权值为8
*/
public static long highestOneBit(long i) {
// HD, Figure 3-1
i |= (i >> 1);
i |= (i >> 2);
i |= (i >> 4);
i |= (i >> 8);
i |= (i >> 16);
i |= (i >> 32);
return i - (i >>> 1);
}
/**
* 二进制最低位1的权值,
* 如5的二进制101,最低位的1在最低位,权值为1
* 10的二进制1010,最低位的1在倒数第二位,权值为2
*/
public static long lowestOneBit(long i) {
// HD, Section 2-1
return i & -i;
}
/**
* 计算出指定值的二进制上高位的零的个数
* 可能这个表达不是很合适,这里的高位就是从前向后数0的个数
*/
public static int numberOfLeadingZeros(long i) {
// HD, Figure 5-6
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;
}
/**
* 指定数的二进制的低位上的0的个数。
* 可能这个表达不是很合适,这里的低位就是从后向前数0的个数
*/
public static int numberOfTrailingZeros(long i) {
// HD, Figure 5-14
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);
}
/**
* 计算指定数的二进制中1的个数
*/
public static int bitCount(long i) {
// HD, Figure 5-14
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;
}
/**
* 循环左移,也就是将i向左移动distance位,
* 当i的移位到达了最高位还没有够distance,那么移位的数就去低位开头,继续移位。
* 所以叫做循环移位。distance可以为负
*/
public static long rotateLeft(long i, int distance) {
return (i << distance) | (i >>> -distance);
}
/**
* 循环右移,也就是将i向右移动distance位,
* 当i的移位到达了最低位还没有够distance,那么移位的数就去高位开头,继续移位。
* 所以叫做循环移位。distance可以为负
*/
public static long rotateRight(long i, int distance) {
return (i >>> distance) | (i << -distance);
}
/**
* 二进制翻转指定值,返回翻转之后的值
*/
public static long reverse(long i) {
// HD, Figure 7-1
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;
}
/**
* 判断传入的值是正数、负数或者零
* -1,负数
* 1,正数
* 0,零
*/
public static int signum(long i) {
// HD, Section 2-7
return (int) ((i >> 63) | (-i >>> 63));
}
/**
* 按照一个Byte位,也就是8位翻转
*/
public static long reverseBytes(long i) {
i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
return (i << 48) | ((i & 0xffff0000L) << 16) |
((i >>> 16) & 0xffff0000L) | (i >>> 48);
}
/**
* 求和
*/
public static long sum(long a, long b) {
return a + b;
}
/**
* 取大值
*/
public static long max(long a, long b) {
return Math.max(a, b);
}
/**
* 取小值
*/
public static long min(long a, long b) {
return Math.min(a, b);
}
/**
* use serialVersionUID from JDK 1.0.2 for interoperability
*/
@Native
private static final long serialVersionUID = 4290774380558885855L;
}