- /*
- 学习后,我们知道利用查表法,十进制数无论转成二进制、八进制、还是十六进制数,
- 都是非常方便的,并且他们都有相似的代码,因此我们可以将这些代码进行提取,总结,
- 写出一个综合的功能:
- */
- class ArrayTest7
- {
- public static void main(String[] args)
- {
- toBa(60);
- System.out.println();
- toHex(60);
- System.out.println();
- toBin(60);
- }
- public static void toBa(int num)
- {
- trans(num,7,3);
- }
- public static void toHex(int num)
- {
- trans(num,15,4);
- }
- public static void toBin(int num)
- {
- trans(num,1,1);
- }
- public static void trans(int num, int base, int offset)
- {
- if(num==0)
- {
- System.out.println(0);
- return ;
- }
- 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 & base;
- arr[--pos] = chs[temp];
- num = num >>> offset;
- }
- for(int x = pos; x < arr.length; x++)
- {
- System.out.print(arr[x]);
- }
- }
- }
复制代码
|
|