zoukankan      html  css  js  c++  java
  • 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));
        }
  • 相关阅读:
    最优贸易 NOIP 2009 提高组 第三题
    Think twice, code once.
    luogu P1378 油滴扩展
    codevs 1002 搭桥
    codevs 1014 装箱问题 2001年NOIP全国联赛普及组
    洛谷P2782 友好城市
    洛谷P1113 杂务
    [HDU1848]Fibonacci again and again
    [POJ2420]A Star not a Tree?
    [SCOI2010]生成字符串
  • 原文地址:https://www.cnblogs.com/xirtam/p/3465430.html
Copyright © 2011-2022 走看看