天天看點

查表法

//查表法

public class ArrayTest6 {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    toHex(6);
}
/*
 *  0 1 2 3 4 5 6 7 8 9 A  B  C  D  E  F ===十六進制中的元素
 *  0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15      
 *  查表法:
 *       将所有的元素臨時儲存起來,建立對應關系
 *       每一次&15 後 的值作為索引去查找建立好的表 就可以找到對應的元素
 *       這樣比 -10 + 'A' 簡單的多
 *      
 *       這個表怎麼建議呢?
 *       可以通過數組的形式來定義
 *       發現終于出結果 但是反着的 想要正過來呢?可以通過StringBuffer reserve() 功能來實作
 *       但還未學習
 * */

public static void toHex(int num)
{   

    char[] chs = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    //定義一個數組臨時容器 
    char[] arr = new char[8];
     for(int x=0;x<8;x++)
     {
         int temp = num & 15;
         System.out.println(chs[temp]);
         arr[x] = chs[temp];

         num =  num >>>4;

     }
     //存儲資料的arr數組進行周遊
    for(int x=arr.length-1;x>=0;x--)
    {
        System.out.print(arr[x]+",");
    }
}
           

}