Skip to content

Latest commit

 

History

History
94 lines (71 loc) · 3.31 KB

File metadata and controls

94 lines (71 loc) · 3.31 KB

Java 程序:八进制到十进制的转换

原文: https://beginnersbook.com/2019/04/java-octal-to-decimal-conversion/

在本文中,我们将看到如何在 Java 中借助示例将八进制转换为十进制。

我们可以通过两种方式将八进制值转换为等效的十进制值:

  1. 使用Integer.parseInt()方法并将基数传递为 8。
  2. 编写我们自己的自定义方法(逻辑)进行转换八进制到十进制。

1. 使用Integer.parseInt()进行 Java 八进制到十进制转换

在下面的示例中,我们将八进制值存储在字符串变量onum中,并使用Integer.parseInt()方法将其转换为十进制值。此方法接受String作为参数,并根据作为参数提供的基本值将其转换为十进制值。

Integer.parseInt()方法中,我们将基数传递为 8,因为八进制数的基值是 8。如果你记得十六进制到十进制转换,我们有传递基数为 16 进行转换。

public class JavaExample{    
   public static void main(String args[]) {
	//octal value
	String onum = "157";

	//octal to decimal using Integer.parseInt()
	int num = Integer.parseInt(onum, 8);

	System.out.println("Decimal equivalent of Octal value 157 is: "+num);
   }
}

输出:

Java octal to decimal conversion example

在上面的例子中,我们对八进制值进行了硬编码,但是如果你想从用户获得八进制值,那么你可以像这样编写逻辑:

import java.util.Scanner;
public class JavaExample{    
   public static void main(String args[]) {
	//octal value
	Scanner scanner = new Scanner(System.in);
	System.out.print("Enter Octal value: ");
	String onum = scanner.nextLine();
	scanner.close();

	//octal to decimal using Integer.parseInt()
	int num = Integer.parseInt(onum, 8);

	System.out.println("Decimal equivalent of value "+onum+" is: "+num);
   }
}

输出:

Enter Octal value: 142
Decimal equivalent of value 142 is: 98

2. 通过编写自定义代码将八进制转换为十进制

在上面的例子中,我们使用Integer.parseInt()方法进行转换,但是我们可以编写自己的逻辑将八进制值转换为等效的十进制值。让我们编写代码:这里我们使用了while循环if..else语句

public class JavaExample{  
   public static int octalToDecimal(int onum){    
	//initializing the decimal number as zero 
	int num = 0;    
	//This value will be used as the power  
	int p = 0;      
	while(true){    
	   if(onum == 0){    
		break;    
	   } else {    
		int temp = onum%10;    
		num += temp*Math.pow(8, p);    
		onum = onum/10;    
		p++;    
	   }    
	}    
	return num;    
   }    
   public static void main(String args[]){        
	System.out.println("Decimal equivalent of octal value 143: "+octalToDecimal(143));       
   }
}

输出:

Java octal to decimal conversion custom logic