2.1Long源码分析

  1. public final class Long extends Number implements Comparable<Long> {  
  2.     public static final long MIN_VALUE = 0x8000000000000000L;//最大值为-2^63  
  3.     public static final long MAX_VALUE = 0x7fffffffffffffffL;//最小值为2^63-1  
  4.     public static final Class<Long>     TYPE = (Class<Long>) Class.getPrimitiveClass("long");  
  5.     public static String toString(long i, int radix) {  
  6.         if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)  
  7.             radix = 10;//Long中进制数出错时,不跑异常,而是默认为10进制  
  8.         if (radix == 10)  
  9.             return toString(i);  
  10.         char[] buf = new char[65];  
  11.         int charPos = 64;  
  12.         boolean negative = (i < 0);  
  13.   
  14.         if (!negative) {//统一转换为负数进行操作  
  15.             i = -i;  
  16.         }  
  17.   
  18.         while (i <= -radix) {  
  19.             buf[charPos--] = Integer.digits[(int)(-(i % radix))];  
  20.             i = i / radix;  
  21.         }  
  22.         buf[charPos] = Integer.digits[(int)(-i)];  
  23.   
  24.         if (negative) {  
  25.             buf[--charPos] = '-';  
  26.         }  
  27.   
  28.         return new String(buf, charPos, (65 - charPos));  
  29.     }  
  30.     public static String toHexString(long i) {//将Long转为16进制  
  31.         return toUnsignedString(i, 4);  
  32.     }  
  33.     public static String toOctalString(long i) {//将Long转为8进制  
  34.         return toUnsignedString(i, 3);  
  35.     }  
  36.     public static String toBinaryString(long i) {//将Long转为2进制  
  37.         return toUnsignedString(i, 1);  
  38.     }  
  39.     private static String toUnsignedString(long i, int shift) {  
  40.         char[] buf = new char[64];  
  41.         int charPos = 64;  
  42.         int radix = 1 << shift;  
  43.         long mask = radix - 1;  
  44.         do {  
  45.             buf[--charPos] = Integer.digits[(int)(i & mask)];//确定最后一位在进制中对应的值  
  46.             i >>>= shift;//右移赋值  
  47.         } while (i != 0);  
  48.         return new String(buf, charPos, (64 - charPos));  
  49.     }  
  50.     public static String toString(long i) {//与Integer的toString方法相同  
  51.         if (i == Long.MIN_VALUE)  
  52.             return "-9223372036854775808";//最小值特殊处理  
  53.         int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);//负数需要多一位用来放负号  
  54.         char[] buf = new char[size];  
  55.         getChars(i, size, buf);  
  56.         return new String(buf, true);  
  57.     }  
  58.     static void getChars(long i, int index, char[] buf) {//使用了与Integer相同的getChars方法,不再分析  
  59.         long q;  
  60.         int r;  
  61.         int charPos = index;  
  62.         char sign = 0;  
  63.   
  64.         if (i < 0) {  
  65.             sign = '-';  
  66.             i = -i;  
  67.         }  
  68.   
  69.         // Get 2 digits/iteration using longs until quotient fits into an int  
  70.         while (i > Integer.MAX_VALUE) {  
  71.             q = i / 100;  
  72.             // really: r = i - (q * 100);  
  73.             r = (int)(i - ((q << 6) + (q << 5) + (q << 2)));  
  74.             i = q;  
  75.             buf[--charPos] = Integer.DigitOnes[r];  
  76.             buf[--charPos] = Integer.DigitTens[r];  
  77.         }  
  78.   
  79.         // Get 2 digits/iteration using ints  
  80.         int q2;  
  81.         int i2 = (int)i;  
  82.         while (i2 >= 65536) {  
  83.             q2 = i2 / 100;  
  84.             // really: r = i2 - (q * 100);  
  85.             r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));  
  86.             i2 = q2;  
  87.             buf[--charPos] = Integer.DigitOnes[r];  
  88.             buf[--charPos] = Integer.DigitTens[r];  
  89.         }  
  90.   
  91.         // Fall thru to fast mode for smaller numbers  
  92.         // assert(i2 <= 65536, i2);  
  93.         for (;;) {  
  94.             q2 = (i2 * 52429) >>> (16+3);  
  95.             r = i2 - ((q2 << 3) + (q2 << 1));  // r = i2-(q2*10) ...  
  96.             buf[--charPos] = Integer.digits[r];  
  97.             i2 = q2;  
  98.             if (i2 == 0break;  
  99.         }  
  100.         if (sign != 0) {  
  101.             buf[--charPos] = sign;  
  102.         }  
  103.     }  
  104.     static int stringSize(long x) {//展示Long的字符串长度  
  105.         long p = 10;  
  106.         for (int i=1; i<19; i++) {每次乘十进行比较  
  107.             if (x < p)  
  108.                 return i;  
  109.             p = 10*p;  
  110.         }  
  111.         return 19;  
  112.     }  
  113.     public static long parseLong(String s, int radix)  
  114.               throws NumberFormatException  
  115.     {  
  116.         if (s == null) {  
  117.             throw new NumberFormatException("null");  
  118.         }  
  119.   
  120.         if (radix < Character.MIN_RADIX) {  
  121.             throw new NumberFormatException("radix " + radix +  
  122.                                             " less than Character.MIN_RADIX");  
  123.         }  
  124.         if (radix > Character.MAX_RADIX) {  
  125.             throw new NumberFormatException("radix " + radix +  
  126.                                             " greater than Character.MAX_RADIX");  
  127.         }  
  128.   
  129.         long result = 0;  
  130.         boolean negative = false;  
  131.         int i = 0, len = s.length();  
  132.         long limit = -Long.MAX_VALUE;  
  133.         long multmin;  
  134.         int digit;  
  135.   
  136.         if (len > 0) {  
  137.             char firstChar = s.charAt(0);  
  138.             if (firstChar < '0') { // Possible leading "+" or "-"  
  139.                 if (firstChar == '-') {  
  140.                     negative = true;  
  141.                     limit = Long.MIN_VALUE;  
  142.                 } else if (firstChar != '+')  
  143.                     throw NumberFormatException.forInputString(s);  
  144.   
  145.                 if (len == 1// Cannot have lone "+" or "-"  
  146.                     throw NumberFormatException.forInputString(s);  
  147.                 i++;  
  148.             }  
  149.             multmin = limit / radix;  
  150.             while (i < len) {  
  151.                 // Accumulating negatively avoids surprises near MAX_VALUE  
  152.                 digit = Character.digit(s.charAt(i++),radix);  
  153.                 if (digit < 0) {  
  154.                     throw NumberFormatException.forInputString(s);  
  155.                 }  
  156.                 if (result < multmin) {  
  157.                     throw NumberFormatException.forInputString(s);//转化为了负数进行计算,所以要用<号  
  158.                 }  
  159.                 result *= radix;  
  160.                 if (result < limit + digit) {  
  161.                     throw NumberFormatException.forInputString(s);  
  162.                 }  
  163.                 result -= digit;  
  164.             }  
  165.         } else {  
  166.             throw NumberFormatException.forInputString(s);  
  167.         }  
  168.         return negative ? result : -result;  
  169.     }  
  170.     public static long parseLong(String s) throws NumberFormatException {//默认转成10进制  
  171.         return parseLong(s, 10);  
  172.     }  
  173.     public static Long valueOf(String s, int radix) throws NumberFormatException {  
  174.         return Long.valueOf(parseLong(s, radix));  
  175.     }  
  176.     public static Long valueOf(String s) throws NumberFormatException  
  177.     {  
  178.         return Long.valueOf(parseLong(s, 10));  
  179.     }  
  180.   
  181.     private static class LongCache {//Long的默认缓存,-128~127,缓存模块与Integer相同  
  182.         private LongCache(){}  
  183.   
  184.         static final Long cache[] = new Long[-(-128) + 127 + 1];  
  185.   
  186.         static {  
  187.             for(int i = 0; i < cache.length; i++)  
  188.                 cache[i] = new Long(i - 128);  
  189.         }  
  190.     }  
  191.     public static Long valueOf(long l) {  
  192.         final int offset = 128;  
  193.         if (l >= -128 && l <= 127) { //在缓存范围内则自动使用缓存中的值  
  194.             return LongCache.cache[(int)l + offset];  
  195.         }  
  196.         return new Long(l);  
  197.     }  
  198.     public static Long decode(String nm) throws NumberFormatException {//用于对未知进制的long型字符串进行解码,根据开头的进制符判断进制,再转换为Long  
  199.         int radix = 10;  
  200.         int index = 0;  
  201.         boolean negative = false;  
  202.         Long result;  
  203.   
  204.         if (nm.length() == 0)  
  205.             throw new NumberFormatException("Zero length string");  
  206.         char firstChar = nm.charAt(0);  
  207.         // Handle sign, if present  
  208.         if (firstChar == '-') {  
  209.             negative = true;  
  210.             index++;  
  211.         } else if (firstChar == '+')  
  212.             index++;  
  213.   
  214.         // Handle radix specifier, if present  
  215.         if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {  
  216.             index += 2;  
  217.             radix = 16;  
  218.         }  
  219.         else if (nm.startsWith("#", index)) {  
  220.             index ++;  
  221.             radix = 16;  
  222.         }  
  223.         else if (nm.startsWith("0", index) && nm.length() > 1 + index) {  
  224.             index ++;  
  225.             radix = 8;  
  226.         }  
  227.   
  228.         if (nm.startsWith("-", index) || nm.startsWith("+", index))  
  229.             throw new NumberFormatException("Sign character in wrong position");  
  230.   
  231.         try {  
  232.             result = Long.valueOf(nm.substring(index), radix);  
  233.             result = negative ? Long.valueOf(-result.longValue()) : result;  
  234.         } catch (NumberFormatException e) {  
  235.             // If number is Long.MIN_VALUE, we'll end up here. The next line  
  236.             // handles this case, and causes any genuine format error to be  
  237.             // rethrown.  
  238.             String constant = negative ? ("-" + nm.substring(index))  
  239.                                        : nm.substring(index);  
  240.             result = Long.valueOf(constant, radix);  
  241.         }  
  242.         return result;  
  243.     }  
  244.     private final long value;  
  245.     public Long(long value) {  
  246.         this.value = value;  
  247.     }  
  248.     public Long(String s) throws NumberFormatException {  
  249.         this.value = parseLong(s, 10);  
  250.     }  
  251.     public byte byteValue() {  
  252.         return (byte)value;  
  253.     }  
  254.     public short shortValue() {  
  255.         return (short)value;  
  256.     }  
  257.     public int intValue() {  
  258.         return (int)value;  
  259.     }  
  260.     public long longValue() {  
  261.         return (long)value;  
  262.     }  
  263.     public float floatValue() {  
  264.         return (float)value;  
  265.     }  
  266.     public double doubleValue() {  
  267.         return (double)value;  
  268.     }  
  269.     public String toString() {  
  270.         return toString(value);  
  271.     }  
  272.     public int hashCode() {//重写hashcode()方法,无符号右移32位后乘value本身  
  273.         return (int)(value ^ (value >>> 32));  
  274.     }  
  275.     public boolean equals(Object obj) {  
  276.         if (obj instanceof Long) {  
  277.             return value == ((Long)obj).longValue();//比较的是value的地址值,所以在缓存范围内的相等,缓存范围外的不等(两个对象指向同一个Long除外)  
  278.         }  
  279.         return false;  
  280.     }  
  281.     public static Long getLong(String nm) {//用于获取系统变量  
  282.         return getLong(nm, null);  
  283.     }  
  284.     public static Long getLong(String nm, long val) {  
  285.         Long result = Long.getLong(nm, null);  
  286.         return (result == null) ? Long.valueOf(val) : result;  
  287.     }  
  288.     public static Long getLong(String nm, Long val) {  
  289.         String v = null;  
  290.         try {  
  291.             v = System.getProperty(nm);  
  292.         } catch (IllegalArgumentException e) {  
  293.         } catch (NullPointerException e) {  
  294.         }  
  295.         if (v != null) {  
  296.             try {  
  297.                 return Long.decode(v);  
  298.             } catch (NumberFormatException e) {  
  299.             }  
  300.         }  
  301.         return val;  
  302.     }  
  303.     public int compareTo(Long anotherLong) {//由于实现了Comparable<Long>接口,所以需要实现compareTo方法  
  304.         return compare(this.value, anotherLong.value);  
  305.     }  
  306.     public static int compare(long x, long y) {  
  307.         return (x < y) ? -1 : ((x == y) ? 0 : 1);  
  308.     }  
  309.     public static final int SIZE = 64;  
  310.     public static long highestOneBit(long i) {//返回二进制最高位的1的值  
  311.         // HD, Figure 3-1  
  312.         i |= (i >>  1);//Long为64位,所以要右移1,2,4,8,16,32,得到一个连续0和连续1组成的二进制数  
  313.         i |= (i >>  2);  
  314.         i |= (i >>  4);  
  315.         i |= (i >>  8);  
  316.         i |= (i >> 16);  
  317.         i |= (i >> 32);  
  318.         return i - (i >>> 1);//i减去i>>>1,即只剩下i的最高位的1(i由两部分组成,前面全为0,后面全为1)  
  319.     }  
  320.     public static long lowestOneBit(long i) {//将i转为2进制返回最右边的1所对应的10进制数,如1100返回4,1000返回8  
  321.         // HD, Section 2-1  
  322.         return i & -i;  
  323.     }  
  324.     public static int numberOfLeadingZeros(long i) {//返回i的开头的0的个数  
  325.         // HD, Figure 5-6  
  326.          if (i == 0)  
  327.             return 64;  
  328.         int n = 1;  
  329.         int x = (int)(i >>> 32);  
  330.         if (x == 0) { n += 32; x = (int)i; }  
  331.         if (x >>> 16 == 0) { n += 16; x <<= 16; }  
  332.         if (x >>> 24 == 0) { n +=  8; x <<=  8; }  
  333.         if (x >>> 28 == 0) { n +=  4; x <<=  4; }  
  334.         if (x >>> 30 == 0) { n +=  2; x <<=  2; }  
  335.         n -= x >>> 31;  
  336.         return n;  
  337.     }  
  338.     public static int numberOfTrailingZeros(long i) {//最右边开始数,有几个连续的0  
  339.         // HD, Figure 5-14  
  340.         int x, y;  
  341.         if (i == 0return 64;  
  342.         int n = 63;  
  343.         y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32);  
  344.         y = x <<16if (y != 0) { n = n -16; x = y; }  
  345.         y = x << 8if (y != 0) { n = n - 8; x = y; }  
  346.         y = x << 4if (y != 0) { n = n - 4; x = y; }  
  347.         y = x << 2if (y != 0) { n = n - 2; x = y; }  
  348.         return n - ((x << 1) >>> 31);  
  349.     }  
  350.      public static int bitCount(long i) {//将i转化为二进制,返回二进制数中1的个数  
  351.         // HD, Figure 5-14  
  352.         i = i - ((i >>> 1) & 0x5555555555555555L);  
  353.         i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L);  
  354.         i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL;  
  355.         i = i + (i >>> 8);  
  356.         i = i + (i >>> 16);  
  357.         i = i + (i >>> 32);  
  358.         return (int)i & 0x7f;  
  359.      }  
  360.     public static long rotateLeft(long i, int distance) {//左旋转i值,比如i=110011,distance=1,返回100111  
  361.         return (i << distance) | (i >>> -distance);  
  362.     }  
  363.     public static long rotateRight(long i, int distance) {//右旋转i值,原理同上  
  364.         return (i >>> distance) | (i << -distance);  
  365.     }  
  366.     public static long reverse(long i) {//全部反转  
  367.         // HD, Figure 7-1  
  368.         i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L;  
  369.         i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L;  
  370.         i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL;  
  371.         i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;  
  372.         i = (i << 48) | ((i & 0xffff0000L) << 16) |  
  373.             ((i >>> 16) & 0xffff0000L) | (i >>> 48);  
  374.         return i;  
  375.     }  
  376.     public static int signum(long i) {用于判断正负值  
  377.         // HD, Section 2-7  
  378.         return (int) ((i >> 63) | (-i >>> 63));  
  379.     }  
  380.     public static long reverseBytes(long i) {//将一个字节作为单位(8位)反转i,  
  381.         i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;  
  382.         return (i << 48) | ((i & 0xffff0000L) << 16) |  
  383.             ((i >>> 16) & 0xffff0000L) | (i >>> 48);  
  384.     }  
  385.     private static final long serialVersionUID = 4290774380558885855L;  
  386. }  

猜你喜欢

转载自blog.csdn.net/qq_18048847/article/details/80348207
今日推荐