class HexadecimalConversion{ public static void main(String[] args) { toBin(6); System.out.println("\n"); System.out.println("------------------------\n"); toHex(-60); System.out.println("\n"); System.out.println("------------------------\n"); toOct(60); } // Dec --> Hex public static void toHex(int num){ trans(num, 15, 4); } // Dec --> Bin public static void toBin(int num){ trans(num,1,1); } public static void toOct(int num){ trans(num,7,3); } public static void trans(int num, int base, int offset){ if(num == 0){ System.out.println(0); return; } char[] chs = {‘0‘,‘1‘,‘2‘,‘3‘, ‘4‘,‘5‘,‘6‘,‘7‘, ‘8‘,‘9‘,‘A‘,‘B‘, ‘C‘,‘D‘,‘E‘,‘F‘}; char[] arr = new char[32]; int pos = arr.length; while(num != 0){ int temp = num & base; arr[--pos] = chs[temp]; num = num >>> offset; } for (int x = pos; x<arr.length; x++) { System.out.print(arr[x]); } } }
原文:http://my.oschina.net/u/2003106/blog/363590