A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

package com.itheima;

public class jinZhiChange
{
            public static void main(String[] args)   
            {  
                toBin(6);  
                toHex(60);  
                toBa(30);  
                System.out.println("Hello World!");  
            }  
            //转2  
            public static void toBin(int num)  
            {  
                trans(num , 1, 1);  
            }  
            //转16  
            public static void toHex(int num)  
            {  
                trans(num , 15, 4);  
            }  
            //转8  
            public static void toBa(int num)  
            {  
                trans(num , 7, 3);  
            }  
            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'};  
                //定义一个临时容器;字符数组在被定义后,它的默认初始化值为'\u0000'相当于空格。
                char[] arr = new char[32];
          
                int pos = arr.length;  
                //接下来就要把查到的字符存到 char[]中,也就是要解决一个存储的问题。
                while(num != 0)  
                {  
                        // num 是移动后前面的二进制位所表示的数,temp 是运算后得到的数
                    int temp = num & base;  
                    arr[--pos] = chs[temp];  
                    num = num >>> offset ;  
                }  
                //对存储结果的char数组遍历 ,
                for(int x = pos ; x < arr.length ; x++)  
                {  
                    System.out.print(arr[x]);  
                }  
          
                System.out.println();  
            }   
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马