一、十进制-->二进制
方法1:
System.out.println(Integer.toBinaryString(60));
方法2:
public static void toBin(int num){
StringBuffer sb = new StringBuffer();
while(num>0){
sb.append(num%2);
num = num / 2;
}
System.out.ptintln(sb.reverse());
}
方法3:(查表法;无局限性,可算负数)
public static void toBin(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 x=pos; x<arr.length; x++){
System.out.println(arr[x]);
}
}
二、十进制-->十六进制
方法1:
System.out.println(Integer.toHexString(60));
方法2:
public static void toHex(int num){
StringBuffer sb = new StringBuffer();
for(int x=0; x<8; x++){
int temp = num & 15;
if(temp>9){
sb.append((char)(temp-10+'A'));
}elae{
sb.append(temp);
{
num = num >>> 4;
}
System.out.ptintln(sb.reverse());
}
方法3:
public static void toHex(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;
}
for(int x=pos; x<arr.length; x++){
System.out.println(arr[x]);
}
}
三、封装查表法实现进制转换:
/*
十进制转二进制
*/
public static void toBin(int num){
trans(num,1,1);
}
/*
十进制转八进制
*/
public static void toOtc(int num){
trans(num,7,3);
}
/*
十进制转十六进制
*/
public static void toHex(int num){
trans(num,15,4);
}
/*
* num 要转进制的数字
* base 基数
* offset 偏移位数
*/
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.println(arr[x]);
}
}