寫了兩種十六進制轉十進制的方式,僅供參考。
基本思路:用十六進制中每一位數乘以對應的權值,再求和就是對應的十進制
方法一:
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
41
42
43
|
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Test { /** * @param: [content] * @return: int * @description: 十六進制轉十進制 */ public static int covert(String content){ int number= 0 ; String [] HighLetter = { "A" , "B" , "C" , "D" , "E" , "F" }; Map<String,Integer> map = new HashMap<>(); for ( int i = 0 ;i <= 9 ;i++){ map.put(i+ "" ,i); } for ( int j= 10 ;j<HighLetter.length+ 10 ;j++){ map.put(HighLetter[j- 10 ],j); } String[]str = new String[content.length()]; for ( int i = 0 ; i < str.length; i++){ str[i] = content.substring(i,i+ 1 ); } for ( int i = 0 ; i < str.length; i++){ number += map.get(str[i])*Math.pow( 16 ,str.length- 1 -i); } return number; } //測試程序 public static void main(String... args) { Scanner input = new Scanner(System.in); String content = input.nextLine(); if (!content.matches( "[0-9a-fA-F]*" )){ System.out.println( "輸入不匹配" ); System.exit(- 1 ); } //將全部的小寫轉化為大寫 content = content.toUpperCase(); System.out.println(covert(content)); } } |
利用了Map中鍵值對應的關系
方法二:
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
41
|
import java.util.Scanner; public class Test2 { /** * @param: [hex] * @return: int * @description: 按位計算,位值乘權重 */ public static int hexToDecimal(String hex){ int outcome = 0 ; for ( int i = 0 ; i < hex.length(); i++){ char hexChar = hex.charAt(i); outcome = outcome * 16 + charToDecimal(hexChar); } return outcome; } /** * @param: [c] * @return: int * @description:將字符轉化為數字 */ public static int charToDecimal( char c){ if (c >= 'A' && c <= 'F' ) return 10 + c - 'A' ; else return c - '0' ; } //測試程序 public static void main(String... args) { Scanner input = new Scanner(System.in); String content = input.nextLine(); if (!content.matches( "[0-9a-fA-F]*" )){ System.out.println( "輸入不匹配" ); System.exit(- 1 ); } //將全部的小寫轉化為大寫 content = content.toUpperCase(); System.out.println(hexToDecimal(content)); } } |
方法二利用了字符的ASCII碼和數字的對應關系
到此這篇關于Java之實現十進制與十六進制轉換案例講解的文章就介紹到這了,更多相關Java之實現十進制與十六進制轉換內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/iczfy585/article/details/92436181