如何将 Java 十六进制转换为十进制

原文:https://www.studytonight.com/java-type-conversion/how-to-convert-java-hexadecimal-to-decimal

在 Java 中,十六进制可以通过integer . parsent()方法或者自定义 Logic 转换成十进制。

1.Integer.parseInt()方法

parseInt() 方法是 Integer 类的一部分,该类根据指定的基数将字符串转换为 Int。

例 1:

这里,十六进制字符串被转换成十进制值。当我们有字符串格式的数据时,这个方法很有用。意思是如果要用parseInt()方法,那么先把数据转换成字符串,然后得到十进制值。

public class StudyTonight
{    
    public static void main(String args[])
    {    
        String b1 = "78F";
        String b2 = "-56578D";
        String b3 = "996B";

        int d1 = Integer.parseInt(b1,16);
        int d2 = Integer.parseInt(b2,16);
        int d3 = Integer.parseInt(b3,16);

        System.out.println("Decimal value is : " +d1);
        System.out.println("Decimal value is : " +d2);
        System.out.println("Decimal value is : " +d3);
    }    
}

小数值为:1935 小数值为:-5658509 小数值为:39275

例 2:

如果您不想使用任何内置方法,请使用此自定义代码,使用自定义逻辑将十六进制值转换为小数。请看下面的例子。

public class StudyTonight
{    
    public static int decimalconvt(String hexadec)
    {  
        String seq = "0123456789ABCDEF";  
        hexadec = hexadec.toUpperCase();  
        int val = 0;  
        for (int i = 0; i < hexadec.length(); i++)  
        {  
            char ch = hexadec.charAt(i);  
            int d = seq.indexOf(ch);  
            val = 16*val + d;  
        }  
        return val;  
    }
    public static void main(String args[])
    {    
        System.out.println("Decimal of 101D is: " +decimalconvt("101D"));  
        System.out.println("Decimal of 156F is: " +decimalconvt("17856D")); 
        System.out.println("Decimal of -17BAED is: " +decimalconvt("-17BAED")); 
    }    
}

101D 的小数为:4125 156F 的小数为:1541485 的小数为-17BAED 的小数为:-15222035