个性化阅读
专注于IT技术分析

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() 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

Java十进制到八进制的转换:自定义逻辑

我们可以使用自定义逻辑在Java中将十进制转换为八进制。

//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

参考文献

  1. Integer.toOctalString()JavaDoc
  2. Integer.toOctalString()srcmini
赞(0)
未经允许不得转载:srcmini » Java将十进制转换为八进制

评论 抢沙发

评论前必须登录!