Java将十进制转换为八进制
我们可以使用
Integer.toOctalString()方法或自定义逻辑将
十进制转换为Java中的八进制。
Java十进制到八进制的转换: Integer.toOctalString()
Integer.toOctalString()方法将十进制转换为八进制字符串。 toOctalString()方法的
签名如下:
public static String toOctalString(int decimal)
让我们看看在Java中将十进制转换为八进制的简单示例。
//Java Program to demonstrate the use of Integer.toOctalString() methodpublic class DecimalToOctalExample1{
public static void main(String args[]){
//Using the predefined Integer.toOctalString() method
//to convert decimal value into octalSystem.out.println(Integer.toOctalString(8));
System.out.println(Integer.toOctalString(19));
System.out.println(Integer.toOctalString(81));
}
}
输出:
Java十进制转换为八进制: 自定义逻辑
我们可以使用自定义逻辑将Java中的
十进制转换为八进制。
//Java Program to demonstrate the decimal to octal conversion
//using custom codepublic class DecimalToOctalExample2{
//creating method for conversion so that we can use it many timespublic static String toOctal(int decimal){
int rem;
//declaring variable to store remainder String octal="";
//declareing variable to store octal
//declaring array of octal numbers char octalchars[]={
'0','1','2','3','4','5','6','7'}
;
//writing logic of decimal to octal conversion while(decimal>0) {
rem=decimal%8;
octal=octalchars[rem]+octal;
decimal=decimal/8;
}
return octal;
}
public static void main(String args[]){
//Calling custom method to get the octal number of given decimal valueSystem.out.println("Decimal to octal of 8 is: "+toOctal(8));
System.out.println("Decimal to octal of 19 is: "+toOctal(19));
System.out.println("Decimal to octal of 81 is: "+toOctal(81));
}
}
输出:
Decimal to octal of 8 is: 10Decimal to octal of 19 is: 23Decimal to octal of 81 is: 121