欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 二进制、八进制、十六进制转换

程序员文章站 2022-08-07 20:55:25
public static void main(String[] args) { System.out.println(toBin(6)); System.out.println(toHex(0)); System.out.println(toOct(8)); } public static Str ......
public static void main(string[] args) {
        system.out.println(tobin(6));
        system.out.println(tohex(0));
        system.out.println(tooct(8));
    }
    
    public static string tobin(int num){
        return trans(num,1,1);
    }

    public static string tohex(int num){
        return trans(num,15,4);
    }

    public static string tooct(int num){
        return trans(num,7,3);
    }

    public static string trans(int num, int base, int offset){
        if (num ==0)
            return "0";
        char[] chs = {'0','1','2','3','4','5','6','7','8','9','a','b','c','b','e','f'};
        char[] arr = new char[32];
        int pos=arr.length;
        while (num!=0){
            int temp = num & base;
            arr[--pos]=chs[temp];
            num = num >>> offset;
        }
        stringbuffer stringbuffer = new stringbuffer();
        for (int i = pos; i < arr.length; i++) {
            stringbuffer.append(arr[i]);
        }
        return stringbuffer.tostring();
    }