/*
需求:将10进制转换为2进制,16进制;
*/
public class toBin
{
public static void main(String[] args)
{
tobin(25);
tohex1(253);
tohex2(253);
tohex3(253);
tohex3(253);
}
//二进制子函数
static void tobin(int num)
{
StringBuffer sb =new StringBuffer();
while(num>0)
{
sb.append(num%2);
num/=2;
}
System.out.println(sb.reverse());
}
/*
16进制子函数(方法1):用除16模16,容器储存,再用if语句转换
*/
static void tohex1(int num)
{
StringBuffer sb =new StringBuffer();
while(num>0)
{
int temp=num%16;
//if语句改变10以上的数为A、B、····
if(temp>9)
sb.append((char)(temp-10+'A'));
else
sb.append(temp);
num/=16;
}
System.out.println(sb.reverse());
}
/*
16进制子函数(方法2):位运算思想
*/
static void tohex2(int num)
{
StringBuffer sb =new StringBuffer();
while(num>0)//或者for(int i=0;i<8;i++)这样在数之前有0
{
int temp=num&15;
if(temp>9)
sb.append((char)(temp-10+'A'));
else
sb.append(temp);
num=num>>>4;//进入下次循环
}
System.out.println(sb.reverse());
}
/*
16进制子函数(方法3):不用if,用数组查表法
*/
static void tohex3(int num)
{
StringBuffer sb =new StringBuffer();
while(num>0)
{
int temp=num%16;
char []arry1= {'0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F'};
sb.append(arry1[temp]);
num/=16;
}
System.out.println(sb.reverse());
}
}