Java教程

Java将八进制转换为十进制

我们可以使用 Integer.parseInt()方法或自定义逻辑将 八进制转换为Java中的十进制

Java八进制到十进制的转换: Integer.parseInt()

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 numberpublic class OctalToDecimalExample1{
    public static void main(String args[]){
        //Declaring an octal numberString octalString="121";
        //Converting octal number into decimalint decimal=Integer.parseInt(octalString,8);
        //Printing converted decimal numberSystem.out.println(decimal);
    }
}
输出:
81
让我们看看Integer.parseInt()方法的另一个示例。
//Shorthand example of Integer.parseInt() methodpublic 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));
    }
}
输出:
81198

Java八进制到十进制的转换: 自定义逻辑

我们可以使用自定义逻辑在Java中将 八进制转换为十进制
//Java Program to demonstrate the conversion of Octal to Decimal
//using custom codepublic class OctalToDecimalExample3{
    //Declaring methodpublic 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 conversionSystem.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: 81Decimal of 23: 19Decimal of 10 is: 8
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4