- /*
- 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’简单的多
- */
- class ArrayTest6
- {
- public static void main(String[] args)
- {
- //toHex(60);
- //toBin(-6);
- toBa(8);
- //System.out.println("Hello World!");
- }
- //优化后的函数调用
- /*
- 十进制-->二进制
- public static void toBin(int num)
- {
- trans(num,1,1);
- }
- */
- //十进制转化成八进制
- public static void toBa(int num)
- {
- trans(num,7,3);
- }
-
- /*
- 十进制转化成十六进制
- public static void toHex(int num)
- {
- trans(num,15,4);
- }
- */
-
- //查表法10 -->16进制
- 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];
- int pos = arr.length -1;
- while(num!=0)
- {
- int temp = num & 15;
- //System.out.print(chs[temp]);
- arr[pos--] =chs[temp];
- num = num >>> 4;
- }
- for (int i =pos+1;i<arr.length ;i++ )
- {
- System.out.print(arr[i]);
- }
- }
- //查表法 10-->2进制
- public static void toBin(int num)
- {
- //定义二进制表
- char [] chs = {'0','1'};
- char [] arr = new char[32];
- int pos = arr.length;
- while (num!=0)
- {
- int temp = num & 1;
- arr[--pos] = chs[temp];
- num = num >>>1;
- }
- for (int i =pos;i <arr.length ;i++ )
- {
- System.out.print(arr[i]);
- }
-
- }
- //进制转化中,有相同的语句,整理优化。
- public static void trans(int num,int x,int y)
- {
- //定义一个通表
- char [] chs = {'0','1','2','3',
- '4','5','6','7',
- '8','9','a','b',
- 'c','d','e','f',};
- char [] arr=new char [32];
- int pos = arr.length;
- while (num!=0)
- {
- int temp = num &x;
- arr[--pos] = chs[temp];
- num = num >>> y;
- }
- for (int i = pos;i <arr.length ;i++ )
- {
- System.out.print(arr[i]);
- }
- }
- }
复制代码 |