Java Octal转Decimal

1 Java Octal转Decimal的介绍

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

2 Java Octal转Decimal的声明

Integer.parseInt() 方法将字符串转换为具有给定基数的int。如果将8作为基数传递,它将八进制字符串转换为十进制。让我们看一下parseInt() 方法的签名:

public static int parseInt(String s,int radix)  

3 Java Octal转Decimal的案例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
//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

4 Java Octal转Decimal的案例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
//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

5 Java Octal转Decimal的案例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
//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

 

热门文章

优秀文章