當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Integer toOctalString()用法及代碼示例


八進製是以8為底的數字係統,在操作中使用數字0到7。八進製被廣泛用於PDP-8等係統的計算中,IBM大型機采用12位,24位或36位字。
Java.lang.Integer.toOctalString()方法是Java中的內置函數,用於將整數參數的字符串表示形式作為基數8中的無符號整數返回。

用法:

public static String toOctalString(int num)

參數:該方法接受整數類型的單個參數num,要求將其轉換為字符串。


返回值:該函數將整數參數的字符串表示形式返回為以8為底的無符號整數。

例子:

 Consider an integer a = 86
 Octal output = 126

Consider an integer a = 186 
Octal output = 272        

以下示例程序旨在說明Integer.toOctalString()方法的用法:
程序1:對於正整數:

// Java program to demonstrate working 
// of Integer.toOctalString() method 
  
import java.lang.*; 
  
public class Geeks { 
  
    public static void main(String[] args) 
    { 
  
        int a = 527; 
        System.out.println("Integral Number = " + a); 
  
        // returns the string representation of the unsigned int value 
        // represented by the argument in octal (base 8) 
        System.out.println("Octal Number = " + Integer.toOctalString(a)); 
    } 
}
輸出:
Integral Number = 527
Octal Number = 1017

程序2:對於負整數:

// Java program to demonstrate working 
// of Integer.toOctalString() method 
  
import java.lang.*; 
  
public class Geeks { 
  
    public static void main(String[] args) 
    { 
  
        int a = -51; 
        System.out.println("Integral Number = " + a); 
  
        // Returns the string representation of the unsigned int value 
        // in octal (base 8) 
        System.out.println("Octal Number = " + Integer.toOctalString(a)); 
    } 
}
輸出:
Integral Number = -51
Octal Number = 37777777715

程序3:對於十進製值或字符串:
注意:每當將十進製數字或字符串作為參數傳遞時,它都會返回一條錯誤消息,導致類型不兼容。

// Java program to demonstrate working 
// of Integer.toOctalString() method 
  
import java.lang.*; 
  
public class Geeks { 
  
    public static void main(String[] args) 
    { 
  
        double a = 18.71; 
  
        // Returns the string representation of the unsigned int value 
        // in octal (base 8) 
        System.out.println("Octal output = " + Integer.toOctalString(a)); 
  
        String b = "63"; 
  
        // Returns the string representation of the unsigned int value 
        // in octal (base 8) 
        System.out.println("Octal output = " + Integer.toOctalString(a)); 
    } 
}

輸出:

prog.java:15:error:incompatible types:possible lossy conversion from double to int
        System.out.println("Octal output = " + Integer.toOctalString(a));
                                                                     ^
prog.java:21:error:incompatible types:possible lossy conversion from double to int
        System.out.println("Octal output = " + Integer.toOctalString(a));
                                                                     ^
Note:Some messages have been simplified; recompile with -Xdiags:verbose to get full output
2 errors


相關用法


注:本文由純淨天空篩選整理自ankita_chowrasia大神的英文原創作品 Integer toOctalString() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。