Java 将八进制转换为十六进制
八进制数 - 八进制数也是可用的数字系统之一。八进制数用8个数字表示,从0到7(0, 1, 2, 3… 7)。八进制数在数字系统中以基数8表示。
十六进制数 - 十六进制数也是可用的数字系统之一。十六进制数用16个数字表示,从0到15(0, 1, 2, 3… 15)。从10到15,用A到F表示。十六进制数在数字系统中以基数16表示。
在这里,我们首先将八进制数转换为相应的十进制数,然后再将该十进制数转换为十六进制数。通过这种方式,我们将八进制数转换为十六进制数。
本文将介绍如何在Java中将八进制数转换为十六进制数。
示例
示例1
Input octal number is 1232.
The decimal converted value of it = 666.
Now the hexadecimal value of 666 = 29A.
示例2
Input octal number is 5454.
The decimal converted value of it = 2860.
Now the hexadecimal value of 2860= B2C.
示例3
Input octal number is 76564.
The decimal converted value of it = 32116.
Now the hexadecimal value of 32116 = 7D74.
步骤
步骤-1 - 通过静态输入或用户输入方法获取输入数字。
步骤-2 - 首先我们使用 ‘Integer.parseInt(octalNumber, 8)’ 方法将给定的八进制数字转换为十进制数字。
步骤-3 - 然后我们使用 ‘Integer.toHexString(decimalNumber)’ 方法将该十进制数字转换为十六进制数字。
步骤-4 - 获得十六进制值后,将该值打印为输出。
多种方法
我们提供了不同的解决方案。
- 使用静态输入值的用户定义方法。
-
使用用户输入值的用户定义方法。
让我们逐个看程序及其输出。
方法1:使用静态输入值的用户定义方法
在这种方法中,我们将一个八进制输入数字声明为静态输入,并将该数字作为参数传递给一个用户定义的方法,然后在方法内部,通过使用算法,我们可以将八进制数字转换为二进制数字。
示例
public class Main {
public static void main(String args[]){
//declare and store a octal number by static input method
String inputNumber = "7654";
//call the user defined method to give the output
octalToHex(inputNumber);
}
//user defined method to convert the octal number into hexadecimal number
public static void octalToHex(String octalNumber){
//declare a variable
//Convert the given Octal number to Decimal number and store it into that variable
int decimalNumber = Integer.parseInt(octalNumber, 8);
//declare a variable
//now convert Decimal number to Hexadecimal number and store it into that variable
String hexadecimalNumber = Integer.toHexString(decimalNumber);
System.out.print("The Hexadecimal Value of "+ octalNumber + " is " + hexadecimalNumber);
}
}
输出
The Hexadecimal Value of 7654 is fac
方法2:使用用户自定义的方法和静态输入值
在这种方法中,我们通过用户输入声明一个八进制输入数字,并将这些数字作为参数传递给用户定义的方法,然后在方法内部通过使用算法将八进制数转换为十六进制数。
示例
import java.util.Scanner;
public class Main {
public static void main(String args[]){
//create object of scanner class
Scanner sc = new Scanner(System.in);
//ask the user to enter an octal number
System.out.print("Enter an Octal Number = ");
//declare and store an octal number by user input method
String inputNumber = sc.nextLine();
//call the user defined method to give the output
octalToHex(inputNumber);
}
//user defined method to convert the octal number into hexadecimal number
public static void octalToHex(String octalNumber) {
//declare a variable
// Convert the given Octal number to Decimal number and store it into that variable
int decimalNumber = Integer.parseInt(octalNumber, 8);
//declare a variable
// now convert Decimal number to Hexadecimal number and store it into that variable
String hexadecimalNumber = Integer.toHexString(decimalNumber);
System.out.print("The Hexadecimal Value of "+ octalNumber + " is " + hexadecimalNumber);
}
}
输出
Enter an Octal Number = 45342
The Hexadecimal Value of 45342 is 4ae2
在本文中,我们探讨了如何使用不同的方法将八进制数转换为十六进制数,使用的是Java语言。