/*
需求:將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());
}
}