import java.util.*;
public class HexToD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入十六进制数");
String hexStr = sc.next();
char[] ch = hexStr.toUpperCase().toCharArray();
charToDec(ch);
}
public static void charToDec (char[] c) {
double[] arr = new double[c.length];
for(int i = 0; i < c.length; i++) {
if(c[i] == 'A') arr[i] = 10;
else if(c[i] == 'B') arr[i] = 11;
else if(c[i] == 'C') arr[i] = 12;
else if(c[i] == 'D') arr[i] = 13;
else if(c[i] == 'E') arr[i] = 14;
else if(c[i] == 'F') arr[i] = 15;
else arr[i] = Double.parseDouble(c[i] + "");
}
double dec = 0;
/*
* 十六进制转十进制:2AF5 => 5 * 16^0 + F * 16^1 + A * 16^2 + 2 * 16^3 = 10997
* mi:16^mi
*/
double mi = 0;
for(int i = arr.length-1; i >= 0; i--) {
dec = dec +(arr[i] * Math.pow(16, mi));
mi++;
}
long h = new Double(dec).longValue(); // 将double转换为long
System.out.println(h);
}
}
蓝桥杯基础练习:十六进制转十进制
最新推荐文章于 2022-02-19 20:22:02 发布