import java.util.Scanner;
public class Hex2Dec
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a hex number");
String hex = input.nextLine();
System.out.println("The decimal value for hex number"+ hex + "is " + hexToDecimal(hex.toUpperCase()));//全部转换成了大写字母
}
public static int hexToDecimal(String hex)
{
int decimalValue = 0;
for(int i = 0;i < hex.length();i++)
{
char hexChar = hex.charAt(i);
decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
/**使用了霍纳算法
* 原来正常算法A B 8 C= 10*16^3+11*16^2+8*16+12
* 改进后:
* ( (10*16+11)*16+8 )*16+12
*/
}
return decimalValue;
}
public static int hexCharToDecimal(char ch)
{
if(ch >= 'A' && ch <= 'Z')//字母
return 10+ ch - 'A';
else //数字
return ch - '0';
}
}