Integer

类声明:public final class Integer extends Number implements Comparable {}
方法:
1.将一个整数转为2到36中的一个进制的静态方法:

 public static String toString(int i, int radix) {
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
            radix = 10;

        /* Use the faster version */
        if (radix == 10) {
            return toString(i);
        }

        char buf[] = new char[33];//4个字节加一个符号
        boolean negative = (i < 0);
        int charPos = 32;

        if (!negative) {//把i变成负数为了保证不溢出,因为负数比正数范围大一
            i = -i;
        }

        while (i <= -radix) {//从最高位依次为buf数组赋值
            buf[charPos--] = digits[-(i % radix)];
            i = i / radix;
        }
        buf[charPos] = digits[-i];//

        if (negative) {//如果I为负数,则为其在前面添加一个‘-’
            buf[--charPos] = '-';
        }

        return new String(buf, charPos, (33 - charPos));
    }

digits数组定义为一个常量字符数组

  final static char[] digits = {
        '0' , '1' , '2' , '3' , '4' , '5' ,
        '6' , '7' , '8' , '9' , 'a' , 'b' ,
        'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
        'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
        'o' , 'p' , 'q' , 'r' , 's' , 't' ,
        'u' , 'v' , 'w' , 'x' , 'y' , 'z'
    };

2.将一个整数无符号字符串

public static String toUnsignedString(int i, int radix) {
        return Long.toUnsignedString(toUnsignedLong(i), radix);
    }
    //在32位的x前面添加32个0
      public static long toUnsignedLong(int x) {
        return ((long) x) & 0xffffffffL;
    }
         public static String toUnsignedString(long i, int radix) {
        if (i >= 0)//正数就调用Long的转为有符号字符串方法,
            return toString(i, radix);
        else {//若进制是2的n次方,则通过移位进行。
            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);
            }
        }

3.使用缓存的valueOf方法。I的范围在-127~128,可以调参数设置最大值,但是缓存数组长度不能超过int最大值。

   public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值