Long源码

Long的源码与Integer的源码几乎是一样的,认真看完Integer的源码,Long源码很快就可以看完,

package java.lang;

import java.lang.annotation.Native;
import java.math.*;
// 实现Comparable接口
public final class Long extends Number implements Comparable<Long> {
    // long的最小值
    @Native public static final long MIN_VALUE = 0x8000000000000000L;
    // long的最大值
    @Native public static final long MAX_VALUE = 0x7fffffffffffffffL;
    
    // 类原始类型 long的 类实例。 
    @SuppressWarnings("unchecked")
    public static final Class<Long>     TYPE = (Class<Long>) Class.getPrimitiveClass("long");
    
    // 传入十进制的长整数,将十进制的i转换成radix进制的字符串
    public static String toString(long i, int radix) {
        // radix在规定的范围外,就按照十进制转换
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
            radix = 10;
        // 如果radix为10就直接调用toString(i)返回
        if (radix == 10)
            return toString(i);
        // 定义一个缓冲字符数组
        char[] buf = new char[65];
        // 定义最大下标
        int charPos = 64;
        // 正负标志位
        boolean negative = (i < 0);
        // 将i转换成负数进行运算
        if (!negative) {
            i = -i;
        }
        // 将转化的每位数放在bug[]中
        while (i <= -radix) {
            buf[charPos--] = Integer.digits[(int)(-(i % radix))];
            i = i / radix;
        }
        buf[charPos] = Integer.digits[(int)(-i)];
        // 加上符号位
        if (negative) {
            buf[--charPos] = '-';
        }
        // 截取buf,返回新的String对象
        return new String(buf, charPos, (65 - charPos));
    }
    
    // 传入十进制的长整数,将十进制的i转换成radix进制的字符串,无符号转换
    public static String toUnsignedString(long i, int radix) {
        // 对i进行判断,为正直接调用toString()
        // i为负,对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);
            }
        }
    }
    
    // 获取到i的无符号BigInteger
    private static BigInteger toUnsignedBigInteger(long i) {
        if (i >= 0L)
            return BigInteger.valueOf(i);
        else {
            // 分别计算高位与底位
            int upper = (int) (i >>> 32);
            int lower = (int) i;
            // 高位左移32位加上底位即为所求的BigInteger
            return (BigInteger.valueOf(Integer.toUnsignedLong(upper))).shiftLeft(32).
                add(BigInteger.valueOf(Integer.toUnsignedLong(lower)));
        }
    }
    
    // 分别为转换成2,8,16进制
    public static String toHexString(long i) {
        return toUnsignedString0(i, 4);
    }
    public static String toOctalString(long i) {
        return toUnsignedString0(i, 3);
    }
    public static String toBinaryString(long i) {
        return toUnsignedString0(i, 1);
    }

    // 2,4,8,16,32进制都是调用的这个方法来实现long按特定的进制转换为String
    static String toUnsignedString0(long val, int shift) {
        // size - 0的个数   -->    有效的位数
        int mag = Long.SIZE - Long.numberOfLeadingZeros(val);
        int chars = Math.max(((mag + (shift - 1)) / shift), 1);
        // 定义一个buf做为缓冲区
        char[] buf = new char[chars];
        // 将val按特定的进制转化成字符数组,放在缓冲区buf中
        formatUnsignedLong(val, shift, buf, 0, chars);
        // 返回一个新的String对象
        return new String(buf, true);
    }
    
    // 将val按特定的进制转化成字符数组,放在缓冲区buf中
    // 返回有效位置下标
    // 这个方法只在toUnsignedString0中使用, offset只能是0
    static int formatUnsignedLong(long val, int shift, char[] buf, int offset, int len) {
        int charPos = len;
        // 通过移位转化为进制
        int radix = 1 << shift;
        int mask = radix - 1;
        // 通过循环将转化后的字符放入buf中
        do {
            buf[offset + --charPos] = Integer.digits[((int) val) & mask];
            val >>>= shift;
        } while (val != 0 && charPos > 0);
        return charPos;
    }
    
    // 将i转换成字符串
    public static String toString(long i) {
        // 如果i为Long的最大值,那么直接返回
        if (i == Long.MIN_VALUE)
            return "-9223372036854775808";
        // i如果为负,变为正求其长度加上符号位,
        int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
        // bug 缓冲字符数组
        char[] buf = new char[size];
        // 将i转换成字符数组放在缓冲区buf中
        getChars(i, size, buf);
        return new String(buf, true);
    }
    
    // 将i转换成字符串,默认十进制转换
    public static String toUnsignedString(long i) {
        return toUnsignedString(i, 10);
    }
    
    // 将i转化为字符数组存放在buf中
    static void getChars(long i, int index, char[] buf) {
        long q;
        int r;
        int charPos = index;
        char sign = 0;
        // 将i转成正数后进行转换
        if (i < 0) {
            sign = '-';
            i = -i;
        }
        // 使用long获得2位数/迭代,直到商符合int
        while (i > Integer.MAX_VALUE) {
            q = i / 100;
            // 2^6+2^5+2^2=64+32+4=100
            // 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];
        }
        // 使用整数获得2位数/迭代
        int q2;
        int i2 = (int)i;
        while (i2 >= 65536) {
            q2 = i2 / 100;
            // 2^6+2^5+2^2=64+32+4=100
            // r = i - 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;
        }
        // sign != 0 说明不为负
        if (sign != 0) {
            buf[--charPos] = sign;
        }
    }

    // 求长整数x的位数, 最大19位
    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为数字字符串s的进制
    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;
        // len > 0 防止 s="" 异常
        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) {
                // 避免MAX_VALUE附近的意外
                digit = Character.digit(s.charAt(i++),radix);
                if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                if (result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                // result增加   --> like result = result * 10(十进制)
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                // 这里是-=而不是+=,因为result第一轮循环时就是负数
                // 最后返回时,negative(表示负)为true返回result,否则返回-result 
                result -= digit;
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
        return negative ? result : -result;
    }
    
    // 将数字字符串转化成long型数据,不指定转化进制,默认10进制
    public static long parseLong(String s) throws NumberFormatException {
        return parseLong(s, 10);
    }
    
    // 无符号转化, radix是指的是s的进制,看parseInt的注释
    public static long parseUnsignedLong(String s, int radix)
                throws NumberFormatException {
        if (s == null)  {
            throw new NumberFormatException("null");
        }
        int len = s.length();
        // len > 0为了防止 s="";抛异常
        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 || // Character.MAX_RADIX中的Long.MAX_VALUE是13位数
                    (radix == 10 && len <= 18) ) { // 基数10中的Long.MAX_VALUE是19位数
                    return parseLong(s, radix);
                }
                
                // ??????????????????不明白这里为什么将最后一位取出来计算
                // 由于上述测试,无需对len进行范围检查,这里是截取到倒数第二位
                long first = parseLong(s.substring(0, len - 1), radix);
                // 这里的charAt(len-1)是取出最后一位
                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型数据,不指定转化进制,默认10进制
    public static long parseUnsignedLong(String s) throws NumberFormatException {
        return parseUnsignedLong(s, 10);
    }
    
    // 通过数字字符串获取long型数据,radix是s的基数
    public static Long valueOf(String s, int radix) throws NumberFormatException {
        return Long.valueOf(parseLong(s, radix));
    }
    
    // // 通过数字字符串获取long型数据,radix是s的基数默认为10
    public static Long valueOf(String s) throws NumberFormatException{
        return Long.valueOf(parseLong(s, 10));
    }
    
    // 内部类,long的缓存
    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型数据,同Integer中范围[-128, 127]获取常量区的数据,范围之外new 对象
    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);
    }
    
    // 解码,将编码的nm,转成long数据
    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);
        // 处理正负标志
        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) {
            //如果number为Long.MIN_VALUE,我们最终会在这里结束。 下一行处理这种情况,并导致重新抛出任何真正的格式错误。
            String constant = negative ? ("-" + nm.substring(index))
                                       : nm.substring(index);
            result = Long.valueOf(constant, radix);
        }
        return result;
    }

    private final long value;
    
    // 将long数据转换为其它类型的数据
    public Long(long value) {
        this.value = value;
    }
    public Long(String s) throws NumberFormatException {
        this.value = parseLong(s, 10);
    }
    public byte byteValue() {
        return (byte)value;
    }
    public short shortValue() {
        return (short)value;
    }
    public int intValue() {
        return (int)value;
    }
    public long longValue() {
        return value;
    }
    public float floatValue() {
        return (float)value;
    }
    public double doubleValue() {
        return (double)value;
    }
    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));
    }
    
    // 比较两个long数据
    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 {
            // 从System中获取
            v = System.getProperty(nm);
        } catch (IllegalArgumentException | NullPointerException e) {
        }
        if (v != null) {
            try {
                return Long.decode(v);
            } catch (NumberFormatException e) {
            }
        }
        // 获取到的为null, 就返回默认值
        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);
    }
    // 无符号比较
    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
            // 答案必须为0或1,具体取决于被除数和除数的相对大小。
            return (compareUnsigned(dividend, divisor)) < 0 ? 0L :1L;
        }
        if (dividend > 0)
            // 被除数和除数都大于0
            return dividend/divisor;
        else {
            // dividend < 0  &  divisor > 0
            return toUnsignedBigInteger(dividend).
                divide(toUnsignedBigInteger(divisor)).longValue();
        }
    }
    
    // 无符号求余
    public static long remainderUnsigned(long dividend, long divisor) {
        // 都大于0
        if (dividend > 0 && divisor > 0) {
            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();
        }
    }
    // long 数据的最大长度
    @Native public static final int SIZE = 64;

    public static final int BYTES = SIZE / Byte.SIZE;
    
    // 返回“最左侧”的位置指定的一个位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值
    // 120 --> 0011 1000   返回   8   --> 0000 1000
    // 129 --> 0100 0001   返回   1   --> 0000 0001
    public static long lowestOneBit(long i) {
        return i & -i;
    }
    
    // 二进制码中,右侧0的个数
    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;
    }
    
    // 二进制码中,左侧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);
    }
    // 返回指定的int值的二进制补码二进制表示中的int数
    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;
    }
    
    // 通过将指定的int值的二进制补码二进制表示旋转指定的位数 long值。 
    // Integer.rotateLeft(8, 5)  --> 8*2^5
    public static long rotateLeft(long i, int distance) {
        return (i << distance) | (i >>> -distance);
    }
    
    // 通过将指定的int值的二进制补码二进制表示旋转指定的位数long值。 
    // Integer.rotateRight(64, 5)  --> 64/(2^5)
    public static long rotateRight(long i, int distance) {
        return (i >>> distance) | (i << -distance);
    }
    
    // 返回由指定的二进制补码表示反转位的顺序而获得的值longt值。 
    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;
    }
    
    // 求long数据i的正负号,-1, 0, 1
    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);
    }

    // 求和
    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);
    }

    @Native private static final long serialVersionUID = 4290774380558885855L;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值