📅  最后修改于: 2020-10-09 00:50:42             🧑  作者: Mango
我们可以使用Integer.parseInt()方法或自定义逻辑在Java中将八进制转换为十进制。
Integer.parseInt()方法将字符串转换为具有给定基数的int。如果将8作为基数传递,它将八进制字符串转换为十进制。让我们看一下parseInt()方法的签名:
public static int parseInt(String s,int radix)
让我们看一下在Java中将八进制转换为十进制的简单示例。
//Java Program to demonstrate the use of Integer.parseInt() method
//for converting Octal to Decimal number
public class OctalToDecimalExample1{
public static void main(String args[]){
//Declaring an octal number
String octalString="121";
//Converting octal number into decimal
int decimal=Integer.parseInt(octalString,8);
//Printing converted decimal number
System.out.println(decimal);
}}
输出:
81
让我们看看Integer.parseInt()方法的另一个示例。
//Shorthand example of Integer.parseInt() method
public class OctalToDecimalExample2{
public static void main(String args[]){
System.out.println(Integer.parseInt("121",8));
System.out.println(Integer.parseInt("23",8));
System.out.println(Integer.parseInt("10",8));
}}
输出:
81
19
8
我们可以使用自定义逻辑在Java中将八进制转换为十进制。
//Java Program to demonstrate the conversion of Octal to Decimal
//using custom code
public class OctalToDecimalExample3{
//Declaring method
public static int getDecimal(int octal){
//Declaring variable to store decimal number
int decimal = 0;
//Declaring variable to use in power
int n = 0;
//writing logic
while(true){
if(octal == 0){
break;
} else {
int temp = octal%10;
decimal += temp*Math.pow(8, n);
octal = octal/10;
n++;
}
}
return decimal;
}
public static void main(String args[]){
//Printing the result of conversion
System.out.println("Decimal of 121 octal is: "+getDecimal(121));
System.out.println("Decimal of 23 octal is: "+getDecimal(23));
System.out.println("Decimal of 10 octal is: "+getDecimal(10));
}}
输出:
Decimal of 121 is: 81
Decimal of 23: 19
Decimal of 10 is: 8