Program for Binary to Octal Conversion in Java
Binary to Octal Conversion
Converting a binary number to octal involves grouping binary digits into sets of three from right to left and converting each set to its octal equivalent.
We will explore three methods to perform this conversion using Java programming.
Method 1: Using Built-in Function
Java provides built-in functions to directly convert binary to octal.
import java.util.Scanner; public class BinaryToOctal { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a binary number: "); String binary = scanner.next(); int decimal = Integer.parseInt(binary, 2); String octal = Integer.toOctalString(decimal); System.out.println("Octal: " + octal); scanner.close(); } }
Example Output:
Enter a binary number: 101101 Octal: 55
Method 2: Using Division by 8
We manually convert binary to decimal and then divide the decimal number by 8 to get the octal equivalent.
import java.util.Scanner; public class BinaryToOctalManual { public static int binaryToDecimal(int binary) { int decimal = 0, base = 1; while (binary > 0) { decimal += (binary % 10) * base; binary /= 10; base *= 2; } return decimal; } public static void decimalToOctal(int decimal) { StringBuilder octal = new StringBuilder(); while (decimal > 0) { octal.insert(0, decimal % 8); decimal /= 8; } System.out.println("Octal: " + (octal.length() > 0 ? octal : "0")); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a binary number: "); int binary = scanner.nextInt(); int decimal = binaryToDecimal(binary); decimalToOctal(decimal); scanner.close(); } }
Example Output:
Enter a binary number: 111001 Octal: 71
Method 3: Using Recursion
We use recursion to first convert binary to decimal and then recursively convert decimal to octal.
import java.util.Scanner; public class BinaryToOctalRecursive { public static int binaryToDecimalRecursive(int binary) { if (binary == 0) return 0; return (binary % 10) + 2 * binaryToDecimalRecursive(binary / 10); } public static void decimalToOctalRecursive(int decimal) { if (decimal == 0) return; decimalToOctalRecursive(decimal / 8); System.out.print(decimal % 8); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a binary number: "); int binary = scanner.nextInt(); int decimal = binaryToDecimalRecursive(binary); System.out.print("Octal: "); if (decimal == 0) System.out.print("0"); else decimalToOctalRecursive(decimal); System.out.println(); scanner.close(); } }
Example Output:
Enter a binary number: 100110 Octal: 46