Java将十六进制转换为十进制
我们可以使用
Integer.parseInt()方法或自定义逻辑将Java中的
十六进制转换为十进制。
Java十六进制到十进制的转换: Integer.parseInt()
Integer.parseInt()方法使用给定的redix将字符串转换为int。 parseInt()方法的
签名如下:
public static int parseInt(String s,int redix)
让我们看看在Java中将十六进制转换为十进制的简单示例。
public class HexToDecimalExample1{
public static void main(String args[]){
String hex="a";
int decimal=Integer.parseInt(hex,16);
System.out.println(decimal);
}
}
输出:
让我们看看Integer.parseInt()方法的另一个示例。
public class HexToDecimalExample2{
public static void main(String args[]){
System.out.println(Integer.parseInt("a",16));
System.out.println(Integer.parseInt("f",16));
System.out.println(Integer.parseInt("121",16));
}
}
输出:
Java十六进制到十进制的转换: 定制逻辑
我们可以使用定制逻辑在Java中将
十六进制转换成十进制。
public class HexToDecimalExample3{
public static int getDecimal(String hex){
String digits = "0123456789ABCDEF";
hex = hex.toUpperCase();
int val = 0;
for (int i = 0; i < hex.length(); i++) {
char c = hex.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
}
return val;
}
public static void main(String args[]){
System.out.println("Decimal of a is: "+getDecimal("a"));
System.out.println("Decimal of f is: "+getDecimal("f"));
System.out.println("Decimal of 121 is: "+getDecimal("121"));
}
}
输出:
Decimal of a is: 10Decimal of f is: 15Decimal of 121 is: 289