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

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);// 12进制最大值,二进制只有0,1,1位右移
    }
 
    // 八进制
    public static void toOct(int num) {
 
        toTran(num, 7, 3);// 72进制最大值,八进制只有0-7最大是7,32进制表示一个八进制右移3
    }
 
    // 十六进制
    public static void toHex(int num) {
 
        toTran(num, 15, 4);// 15是十六进制最大值,十六进制只有0-15最大是15,42进制表示一个八进制右移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();
    }
 
}
全部评论

相关推荐

水墨不写bug:疑似没有上过大学
点赞 评论 收藏
分享
05-16 11:16
已编辑
东华理工大学 Java
牛客73769814...:盲猜几十人小公司,庙小妖风大,咋不叫她去4️⃣呢😁
牛客创作赏金赛
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务