由其他進制轉換為十進制比較簡單,下面著重談一談十進制如何化為其他進制。
1.使用Java帶有的方法Integer,最簡單粗暴了,代碼如下
1
2
3
4
5
6
7
8
9
10
11
12
13
|
//使用java提供的方法 //但僅局限于比較常用的二進制、八進制、十六進制 public static String trans1( int num, int radix) { if (radix == 2 ) return Integer.toBinaryString(num); else if (radix == 8 ) return Integer.toOctalString(num); else if (radix == 16 ) return Integer.toHexString(num); return null ; } |
2.使用數組進行交換,貼碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
//使用數組的形式進行轉換 public static void trans2( int num, int radix) { System.out.println(num+ "轉成" +radix+ "進制數為:" ); //創建數組,32位 char [] arr = new char [ 32 ]; //創建參考字符數組 char [] ch = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'A' , 'B' , 'C' , 'D' , 'E' , 'F' }; //指針,從數組最后開始 int pos = 32 ; //開始循環計算num和radix的商和余數 while (num > 0 ) { arr[--pos] = ch[num % radix]; num /= radix; /* * 這里是針對二進制、八進制和十六進制進行的移位運算 arr[--pos] = ch[num&(radix-1)]; if(radix == 2) num >>= 1; else if(radix == 8) num >>= 3; else if(radix == 16) num >>= 4; */ } //輸出有效的進制數 for ( int i = pos; i < 32 ; i++) System.out.print(arr[i]); System.out.println(); } |
3.使用StringBuilder類型,貼碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
//使用StringBuilder進行轉換 public static String trans3( int num, int radix) { //使用StringBuilder的reverse方法 StringBuilder sb = new StringBuilder(); while (num > 0 ) { //把除以基數的余數存到緩沖區中 sb.append(num % radix); num /= radix; } return sb.reverse().toString(); } |
以上就是Java 3種方法實現進制轉換的詳細內容,更多關于Java 進制轉換的資料請關注服務器之家其它相關文章!
原文鏈接:https://www.cnblogs.com/xiaolongdejia/archive/2004/01/13/10867121.html