Java學習(22) -- 源碼閱讀(Long)

/**
 * auther: jiyx
 * date: 2018/9/18.
 */
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<Long> TYPE = (Class<Long>) 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;
    }

    /**
     * 根據基數,返回字符串代表的數字的十進制形式
     * <p>示例:
     * <blockquote><pre>
     * 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進制
     * <p>
     * <blockquote>
     * <dl>
     * <dt><i>DecodableString:</i>
     * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
     * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
     * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
     * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
     * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
     */
    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;
}

轉自:https://www.jianshu.com/p/5747d003a082

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章