Java进制转换

其他转10进制

     System.out.println(Integer.parseInt("10", 2));// bin
        System.out.println(Integer.parseInt("12", 3));
        System.out.println(Integer.parseInt("742", 8));// oct
        System.out.println(Integer.parseInt("12A", 16));// hex

10进制转2,8,16

     System.out.println(Integer.toBinaryString(255));
        System.out.println(Integer.toHexString(255));
        System.out.println(Integer.toOctalString(255));

 

jdk代码实现。

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'
    };


  public static String toHexString(int i) {
    return toUnsignedString(i, 4);
    }

    
    public static String toOctalString(int i) {
    return toUnsignedString(i, 3);
    }

    
    public static String toBinaryString(int i) {
    return toUnsignedString(i, 1);
    }

    
    private static String toUnsignedString(int i, int shift) {
    char[] buf = new char[32];
    int charPos = 32;
    int radix = 1 << shift;
    int mask = radix - 1;
    do {
        buf[--charPos] = digits[i & mask];
        i >>>= shift;
    } while (i != 0);

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

 

 

posted @ 2013-12-09 14:54  带狗狗带  Views(250)  Comments(0Edit  收藏  举报