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(); }}
新聞熱點
疑難解答