给你三种转换的方法(num=num>>>4,“>>>”表示无符号右移,而“>>”表示右移),希望能帮到你:- class ArrayTestToHex
- {
- public static void main(String[] args)
- {
- System.out.println("输入一个要转成16进制的数:");
- Scanner in = new Scanner(System.in);
- int num=in.nextInt();
- System.out.println("第一种方法:");
- toHex(num);
- System.out.println("第二种方法:");
- toHex_1(num);
- System.out.println("第三种方法:");
- toHex_2(num);
- }
- public static void toHex(int num)
- {
- 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[8];
- int pos = arr.length;
- while(num!=0)
- {
- int temp = num&15;
- arr[--pos] = chs[temp];
- num = num >>> 4;
- }
-
- System.out.println("pos="+pos);
- for(int x=pos ;x<arr.length; x++)
- System.out.print(arr[x]);
- }
-
- public static void toHex_1(int num)
- {
- char[] chs = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
- for(int x=0 ; x<8; x++)
- {
- int temp = num & 15;
- System.out.print(chs[temp]);
- num = num >>> 4;
- }
- }
-
- public static void toHex_2(int num)
- {
- for(int x=0; x<8; x++)
- {
- int temp = num & 15;
- if(temp>9)
- System.out.print((char)(temp-10+'A'));
- else
- System.out.print(temp);
- num = num >>> 4;
- }
- }
- }
复制代码
|