十进制转换为二进制,八进制,十六进制的简单实现

public class Demo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入十进制数:");
        int i = input.nextInt();
        System.out.println(two(i) + " " + eight(i) + " " + sixteen(i));
    }

    /**
     * 转为二进制
     * @param cal1
     * @return
     */
    public static String two(int cal1){
        String a = "";
        while (cal1 != 0){
            a = (cal1 % 2) + a;
            cal1 = cal1 / 2;
        }
        return a;
    }

    /**
     * 转为八进制
     * @param cal2
     * @return
     */
    public static String eight(int cal2){
        String a = "";
        while (cal2 != 0){
            a = cal2 % 8 + a;
            cal2 = cal2 / 8;
        }
        return a;
    }

    /**
     * 转为十六进制
     * @param cal3
     * @return
     */
    public static String sixteen(int cal3){
        StringBuffer s = new StringBuffer();
        String a;
        char []b = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        while(cal3 != 0){
            s = s.append(b[cal3%16]);
            cal3 = cal3/16;
        }
        a = s.reverse().toString();
        return a;
    }

}
posted @ 2020-04-07 22:05  笔架山Code  阅读(207)  评论(0编辑  收藏  举报