天天看點

十進制轉成十六進制數 查表法

---------------------- ASP.Net+Android+IOS開發、.Net教育訓練、期待與您交流! ----------------------

/*
  十進制轉成十六進制數
  查表法
*/
class  ArrayDemo
{
	public static void main(String[] args) 
	{
		String hex = toHex(10);
		System.out.println(hex);
		System.out.println(Integer.toHexString(10));
	}

	//定義函數計算進制,傳回字元串,未知資料轉換的數
	public static String toHex(int num){
		//定義數組,當作表,使用
		char[] table = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};


		//定義數組,存儲查表後的字元
		char[] result = new char[8];

		//開始計算十六進制了
		//定義指針,指向結果數組的最後索引
		int pos = result.length - 1;
		while(num!=0){
		    num & 15
			int temp = num & 15 ;
			//将結果temp,作為索引,查表
			//存儲到結果的數組中,從最後的索引存儲
			
			result[pos--]=table[temp];
			//位移
			num = num >>> 4;
		}
		String hex = "";
		for(int x = pos+1 ; x < result.length; x++){
		     hex = hex+result[x];
		}
		return hex;
	}
}
           

---------------------- ASP.Net+Android+IOS開發、.Net教育訓練、期待與您交流! ----------------------

繼續閱讀