java学习进制转换之查表法
10进制转16进制,以及10进制转2进制,还有10进制转8进制,这些转换如果按照常规思路的话,会灰常的麻烦。
我们来看一下 10进制转16进制:
假如这里有一个十进制数字:35,我们的需求就是把这个35转成16进制的。
思路:先把35转换成二进制,然后二进制再转换16进制。
代码:
class SearchTable { public static void main(String[] args) { String[] s = searchTable(35,3,7); /** * *for(int i = 0; i< arr.length ; i++) *{ * * System.out.println(arr[i]); * *} */ for(int i = 0; i<8 ; i++) { System.out.print(s[i]); } } public static String[] searchTable(int num,int offset,int mask) { String[] table = {"","1","2","3","4","5","6","7","8","9","a","b","c","d","e"}; String[] output = new String[8]; int [] arrtemp = new int[8]; for(int i = arrtemp.length-1 ; i>=0 ; i--){ arrtemp[i] = num&mask; num = num>>>offset; output[i] =table[arrtemp[i]]; } return output; } }
温馨提示,当写程序的时候尽量保证一个量变化否则,会把自己绕进去的。
/** *反面示例 */ class SearchTable { public static void main(String[] args) { String s = searchTable(35,3,7); /** * *for(int i = 0; i< arr.length ; i++) *{ * * System.out.println(arr[i]); * *} */ System.out.print(s); } public static String searchTable(int num,int offset,int mask) { String[] table = {"","1","2","3","4","5","6","7","8","9","a","b","c","d","e"}; String output = ""; int [] arrtemp = new int[8]; for(int i =0 ; i<arrtemp.length-1 ; i++){ arrtemp[i] = num&mask; num = num>>>offset; System.out.println("---"+i+"--"); System.out.println(arrtemp[7-i]); System.out.println(table[arrtemp[i]]); System.out.println("---"+i+"--end"); output += table[arrtemp[i]]; } return output; } }