Java 十六进制转十进制

时间:2021-03-15 19:26:13

public static int hexToDecimal(String hex) {

int decimalValue = 0;
for (int i = 0; i < hex.length(); i++) {
decimalValue = decimalValue * 16 + hexCharToDecimal(hex.charAt(i));
}
return decimalValue;
}

public static int hexCharToDecimal(char ch) {

if (ch <= 'F' && ch >= 'A') {
return 10 + ch - 'A';
}
else {
return ch - '0';
}
}

System.out.println("The decimal number for hex " + hexString
+ " is " + hexToDecimal(hexString.toUpperCase()));