如何将 Java 八进制转换成十进制
原文:https://www.studytonight.com/java-type-conversion/how-to-convert-java-octal-to-decimal
在 Java 中,八进制值可以通过integer . parsent()方法或者自己的自定义代码转换成十进制值。让我们看看例子。
1.Integer.parseInt()
方法
parseInt() 方法是 Integer 类的一部分,该类根据指定的基数将字符串转换为 Int。
例 1:
这里,使用parseInt()
方法将八进制字符串值转换为十进制值。请看下面的例子。
public class StudyTonight
{
public static void main(String args[])
{
String o1 = "75";
String o2 = "-56573";
String o3 = "336";
int d1 = Integer.parseInt(o1,8);
int d2 = Integer.parseInt(o2,8);
int d3 = Integer.parseInt(o3,8);
System.out.println("Decimal value is : " +d1);
System.out.println("Decimal value is : " +d2);
System.out.println("Decimal value is : " +d3);
}
}
小数值为:61 小数值为:-23931 小数值为:222
例 2:
八进制值可以使用自定义逻辑转换为小数。当您不想使用任何内置方法时,这很有用。
public class StudyTonight
{
public static int decimalconvt(int oct)
{
int dec = 0;
int n = 0;
while(true)
{
if(oct == 0)
{
break;
}
else
{
int tmp = oct%10;
dec += tmp*Math.pow(8, n);
oct = oct/10;
n++;
}
}
return dec;
}
public static void main(String args[])
{
System.out.println("Decimal of 101 is: " +decimalconvt(101));
System.out.println("Decimal of 1756 is: " +decimalconvt(1756));
System.out.println("Decimal of -1743 is: " +decimalconvt(-1743));
}
}
101 的小数为:65 1756 的小数为:1006 1743 的小数为:-995