關於java十進制轉變二進制,八進制,十六進制的不同方法及代碼

關於java十進制轉變二,八,十六的不同方法及代碼

下面是我今天上午剛剛學習的,現在來總結並分享給大家,新手上路,如有不對多多指教
這也是我的第一篇博客,大二在校生一枚,初學java,一起進步。

1:十進制轉變二進制

方法一:直接法

public static void tobin_1 (int a)
	{
		StringBuffer sb =new StringBuffer();
		
		while(a>0)
		{
			sb.append(a%2);
			a=a/2;
		}
		System.out.print(sb.reverse());
	}

方法二:查表法

public static void tobin_2 (int a)
	{
		char [] list={'0','1'};
		char[] arr=new char[32];
		int pa=0;
		while (a!=0)
		{
			int q=a&1;
			arr[pa++]=list[q];
			a=a>>>1;
		}
		for(int y=pa-1;y>=0;y--)
		{
			System.out.print(arr[y]);
		}		
	}

1:十進制轉變十六進制

方法一:直接法(改進)

public static void tosl_1(int a)
	{
		StringBuffer sb =new StringBuffer();
		for (int x=0;x<8;x++)
		{
			int q=a & 15;
			if(q>9)
				sb.append((char)(q-10+'A'));
			else 
				sb.append(q);
			a = a >>> 4;
		}
		System.out.println(sb.reverse());
	}

方法二:直接法

public static void tosl_1(int a)
	{
		StringBuffer sb =new StringBuffer();
		for (int x=0;x<8;x++)
		{
			int q=a & 15;
			if(q>9)
				System.out.print((char)(q-10+'A'));
			else 
				System.out.print(q);
			a = a >>> 4;
		}
		System.out.println(sb.reverse());
	}

方法三:查表法

public static void tosl_2(int a)
	{
		char [] list={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
		int pa=0;
		char [] arr = new char [8];
		while (a!=0)
		{
			int b=a&15;
			arr[pa++]=list[b];
			
			a=a>>>4;
			
		}
		for(int y=pa-1;y>=0;y--)
		{
			System.out.print(arr[y]);
		}	
	}

轉八進制也一樣如此,不打了,下面來展示一下優化後的代碼。
尋找幾個代碼的共性:數組arr[32]足夠二進制,八進制及十六進制使用以及都要存入數組,移位,與一個數。
異性:它們所與,移,輸入的數不一樣。
可以得到如下優化代碼

public static void qqq(int a,int x,int z)
//a:輸入的數,x:所與的數,z:所移位數
	{
		char [] list={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
		int pa=0;//作爲指針,做下標
		char [] arr = new char [32];
		while (a!=0)
		{
			int b=a&x;
			arr[pa++]=list[b];
			
			a=a>>>z;
			
		}
		for(int y=pa-1;y>=0;y--)
		{
			System.out.print(arr[y]);
		}	
		System.out.println(' ');
	}

然後進行函數的嵌套

//十進制——>二進制
	public static void tobin_3 (int a)
	{
		qqq(a, 1, 1);
	}
/十進制——>八進制
	public static void toba(int a)
	{
		qqq(a, 7, 3);
	}
//十進制——>十六進制
	public static void tosl_3(int a)
	{
		qqq(a, 15, 4);
	}

這樣使函數更簡潔。
新手文章,如有不足多多指教,一起進步

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章