Fork me on GitHub

将一个十进制转换为二进制,八进制,十六进制

package com.db2;

/**
 * 将一个十进制转换为二进制,八进制,十六进制
 * 
 * @author denny
 *
 */
public class Demo2 {

    public static void main(String[] args) {
        toBin(6);
        toBin(-6);
        toOct(60);
        toOct(-60);
        toHex(60);
        toHex(-60);
    }

    // 转换2进制
    public static void toBin(int num) {

        toTran(num, 1, 1);// 1是2进制最大值,二进制只有0,1,1位右移
    }

    // 八进制
    public static void toOct(int num) {

        toTran(num, 7, 3);// 7是2进制最大值,八进制只有0-7最大是7,3位2进制表示一个八进制右移3位
    }

    // 十六进制
    public static void toHex(int num) {

        toTran(num, 15, 4);// 15是十六进制最大值,十六进制只有0-15最大是15,4位2进制表示一个八进制右移4位
    }

    // 转换函数
    private static void toTran(int num, int base, int offset) {// num要转换的数,求与的数,右移的数
        char[] ch = { '0','1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; // 十六进制元素同时包含2,进制,八进制
        // 存储转换过的数 //最大只有32位
        char[] arr = new char[32];
        // 定义控制数组的下标
        int pos = arr.length;
        // 开始转换
        while (num != 0) {
            int temp = num & base;// 与位
            arr[--pos] = ch[temp]; // 找到并存储
            num = num >>> offset;
        }
        // 输出
        for (int i = pos; i < arr.length; i++) {
            System.out.print(arr[i]);
        }
        System.out.println();
    }

}

 

posted @ 2015-09-07 09:29  森林森  阅读(1009)  评论(0编辑  收藏  举报