class ScaleTest
{
public static void main(String[] args)
{
toHex(60);
System.out.println();
toOctal(60);
System.out.println();
toBinary(6);
}
//十进制转换成二进制
public static void toBinary(int num)
{
trans(num,1,1);
}
//十进制转换成八进制
public static void toOctal(int num)
{
trans(num,7,3);
}
//十进制转换成十六进制
public static void toHex(int num)
{
trans(num,15,4);
}
public static void trans(int num,int a, int b)
{
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 index = num & a;//获取num的嘴小a位的值
arr[--pos] = chs[index];//将得到的值存储到临时容的最后一位角标上
num = num >>> b;//将num向右偏移b位
}
for (int x=pos; x<arr.length; x++)//对临时容器进行遍历
{
System.out.print(arr[x]);
}
}
} |
|