/*
* 现实中转换方法都是返回字符串的
*/
public class Test {
public static void main(String[] args) {
toBin_2(-6);
// toHex_2(60);
}
/*
* 十进制转二进制
*/
public static void toBin(int num) {
StringBuffer sb = new StringBuffer();
while (num > 0) {
sb.append(num % 2);
num /= 2;
}
System.out.println(sb.reverse());
}
/*
* 查表法十进制转二进制
*/
public static void toBin_2(int num) {
/*
* char[] chs = { '0', '1' }; char[] arr = new char[32]; int pos =
* arr.length; while (num != 0) { int temp = num & 1; arr[--pos] =
* chs[temp]; num = num >>> 1; } for (int i = pos; i < arr.length; i++)
* { System.out.print(arr[i]); }
*/
trans(num, 1, 1);
}
/*
* 十进制转十六进制
*/
public static void toHex(int num) {
StringBuffer sb = new StringBuffer();
for (int x = 0; x < 8; x++) { // 循环8次是因为int是32bit没4bit转换成一个16进制
int temp = num & 15; // & 15 就可以算出最后的4bit
if (temp > 9) {
sb.append((char) (temp - 10 + 'A'));
} else {
sb.append(temp);
}
num = num >>> 4; // 每算出最后4位,无符号右移4位,一定是无符号的右移! }
}
System.out.println(sb.reverse());
}
/*
* 查表法 十进制转十六进制
*/
public static void toHex_2(int num) {
/*
* char[] chs = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
* 'B', 'C', 'D', 'E', 'F' }; char[] arr = new char[8]; int pos =
* arr.length; // 指针 while (num != 0) { int temp = num & 15; arr[--pos]
* = chs[temp]; num = num >>> 4; } System.out.println("pos=" + pos); for
* (int i = pos; i < arr.length; i++) { System.out.print(arr[i] + ",");
* }
*/
trans(num, 15, 4);
}
/*
* 进制方法优化,抽取共同部分
*/
public static void trans(int num, int base, int offset) { // base 要&的数
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 i = pos; i < arr.length; i++) {
System.out.print(arr[i]);
}
}
}
java进制转换在数组中的体现
最新推荐文章于 2022-05-12 16:04:02 发布