Java Decimal转Octal

1 Java Decimal转Octal的介绍

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

2 Java Decimal转Octal的声明

Integer.toOctalString() 方法将十进制转换为八进制字符串。toOctalString() 方法的签名如下:

public static String toOctalString(int decimal)  

3 Java Decimal转Octal的案例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
//Java Program to demonstrate the use of Integer.toOctalString() method  
public class DecimalToOctalExample1{  
public static void main(String args[]){  
//Using the predefined Integer.toOctalString() method  
//to convert decimal value into octal  
System.out.println(Integer.toOctalString(8));  
System.out.println(Integer.toOctalString(19));  
System.out.println(Integer.toOctalString(81));  
}}  

输出结果为:

10
23
121

4 Java Decimal转Octal的案例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
//Java Program to demonstrate the decimal to octal conversion  
//using custom code  
public class DecimalToOctalExample2{    
//creating method for conversion so that we can use it many times  
public 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 value  
System.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: 10
Decimal to octal of 19 is: 23
Decimal to octal of 81 is: 121

 

热门文章

优秀文章