liunanjava
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();
    }

}

 

分类:

技术点:

相关文章:

  • 2021-10-07
  • 2021-10-12
  • 2021-11-28
  • 2021-11-04
  • 2021-10-07
  • 2021-11-08
  • 2021-11-07
猜你喜欢
  • 2021-11-28
  • 2021-10-12
  • 2021-09-27
  • 2021-11-09
  • 2021-10-16
  • 2021-11-27
  • 2021-10-17
相关资源
相似解决方案