package cn.other;
/**
*
*進制轉換.
*/
public class ConverBin {
public static void main(String[] args) {
System.out.println(toBin(-6));
System.out.println(Integer.toBinaryString(-6));
System.out.println(Integer.toHexString(60));
}
/*
* 十進制-->十六進制
*/
public static String toHex(int num) {
return trans(num, 15, 4);
}
/*
* 十進制-->二進制
*/
public static String toBin(int num) {
return trans(num, 1, 1);
}
/*
* 十進制-->八進制。
*/
public static String toOc(int num) {
return trans(num, 7, 3);
}
public static String trans(int num, int base, int offset) {
// 定義元素表。
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) {
// 對num進行&運算獲取指定的二進制位。
int temp = num & base;
// 將temp作爲角標,去查表,將查表後的元素存儲到臨時容器中。
arr[--pos] = chs[temp];
// 將num進行右移,取下一段二進制位。
num = num >>> offset;
}
// 將arr數組中的有效元素變成字符串,使用到了String對象。
return new String(arr, pos, arr.length - pos);
}
}
【JAVA核心技術】進制轉換
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.