概念:将所有的元素临时存储起来,建立对应关系,每一次&15之后的值作为索引去查建立好的表。就可以找到对应的元素。这样比-10+‘a’简单的多。
代码:
class Trans{
public static void main(String[] args)
{
toBin(0);
System.out.println("---------------------------------------");
toBin(60);
System.out.println("---------------------------------------");
toBa(60);
System.out.println("---------------------------------------");
toHex(60);
System.out.println("---------------------------------------");
}
//二进制
public static void toBin(int num)
{
trans(num,1,1);
}
//八进制
public static void toBa(int num)
{
trans(num,7,3);
}
//十六进制
public static void toHex(int num)
{
trans(num,15,4);
}
public static void trans(int num,int base,int offset){
if(num==0){
System.out.println(0);
}else{
char[] arr =new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char[] temp = new char[32];
int pos = temp.length;
while(num!=0){
int x = num&base;
temp[--pos] = arr[x];
num=num>>>offset;
}
for(int i = pos;i<temp.length;i++){
System.out.print(temp[i]+",");
}
System.out.println("");
}
}
}
/*
//查表法二进制
public static void tobin(int num){
//定义一个二进制表
char[] arr = new char[]{'0','1'};
//定义一个临时存储容器
char[] temp = new char[32];
//定义一个操作数组的指针
int pos = temp.length;
while(num!=0){
int x = num&1;
temp[--pos] = arr[x];
num=num>>>1;
}
for(int i=pos;i<temp.length;i++)
{
System.out.print(temp[i]+",");
}
}
//查表法十六进制
public static void toHex(int num)
{
char[] arr =new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char[] temp = new char[8];
int pos = temp.length;
while(num!=0){
int x = num&15;
temp[--pos] = arr[x];
num=num>>>4;
}
for(int i = pos;i<temp.length;i++){
System.out.print(temp[i]+",");
}
}
*/ |
|