Java程式將二進位制轉換為八進位制
二進位制數 - 根據基值,存在多種型別的數字系統。二進位制數就是其中之一。二進位制數基本上由兩個數字表示,即一 (1) 和零 (0)。二進位制數在數字系統中表示為以 2 為基數。
八進位制數 - 八進位制數也是一種可用的數字系統。八進位制數用 8 個數字表示,從 0 到 7 (0、1、2、3... 7)。八進位制數在數字系統中表示為以 8 為基數。
這裡我們將二進位制數轉換為八進位制數,但為此,我們必須首先將二進位制數轉換為十進位制數,以便之後可以使用toOctalString() 方法將該十進位制數轉換為八進位制數。
Binary Number → Decimal Number → Octal Number
toOctalString() 方法是Integer 類的內建函式。
語法
public static String toOctalString(int i)
問題陳述
編寫一個Java程式,將二進位制數轉換為八進位制數 -
輸入-1
Input Binary number is 101011.
輸出-1
By converting into decimal = 43. Now converting it to octal = 53
輸入-2
Input Binary number is 1111111.
輸出-2
By converting into decimal = 127 Now converting it to octal = 177
輸入-3
Input Binary number is 11001100.
輸出-3
By converting into decimal = 204. Now converting it to octal = 314.
將二進位制轉換為八進位制的方法
我們提供了不同方法的解決方案 -
方法-1:使用帶靜態輸入值的自定義方法
在這種方法中,我們宣告一個長變數,用程式中的二進位制數對其進行初始化,並將此數字作為引數傳遞給自定義方法,然後在方法內部,透過使用演算法,我們可以將二進位制數轉換為八進位制數。
- 開始
- 匯入java.util.*並定義Main 類。
- 宣告一個具有靜態值的long變數binary。
- 將二進位制轉換為十進位制,然後將十進位制轉換為八進位制並列印值。
- 停止
示例
以下是使用靜態輸入方法將二進位制數轉換為八進位制數的示例 -
import java.util.*; public class Main { public static void main(String[] args){ long binary=1010; binToDec(binary); } public static void binToDec(long binaryNumber){ int decNum = 0, i = 0; while (binaryNumber > 0) { decNum += Math.pow(2, i++) * (binaryNumber % 10); binaryNumber /= 10; } System.out.println("In Decimal="+decNum); decToOct(decNum); } public static void decToOct(long decNum){ String octalString = Long.toOctalString(decNum); int octalNumber = Integer.parseInt(octalString); System.out.println("In octal="+octalNumber); } }
輸出
In Decimal=10 In octal=12
方法-2:使用帶使用者輸入值的自定義方法
在這種方法中,我們宣告一個二進位制輸入數,並將此數字作為引數傳遞給自定義方法,然後在方法內部,透過使用演算法,我們可以將二進位制數轉換為十六進位制數。
- 開始
- 匯入java.util.*並定義Main 類。
- 獲取二進位制數的使用者輸入。
- 呼叫使用者定義的方法進行轉換。
- 將二進位制轉換為十進位制,然後將十進位制轉換為八進位制並列印值。
- 停止。
示例
以下是使用使用者定義的方法將二進位制數轉換為八進位制數的示例 -
import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.print("Enter a binary number: "); long binary=sc.nextLong(); binToDec(binary); } public static void binToDec(long binaryNumber){ int decNum = 0, i = 0; while (binaryNumber > 0) { decNum += Math.pow(2, i++) * (binaryNumber % 10); binaryNumber /= 10; } System.out.println("In Decimal="+decNum); decToOct(decNum); } public static void decToOct(long decNum){ String octalString = Long.toOctalString(decNum); int octalNumber = Integer.parseInt(octalString); System.out.println("In octal="+octalNumber); } }
輸出
Enter a binary number: 1111 In Decimal=15 In octal=17
在本文中,我們探討了如何透過使用不同的方法在 Java 中將二進位制轉換為八進位制。
廣告