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
We first convert the binary number to decimal and then use Java's built-in function to convert it 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); System.out.println("Octal: " + Integer.toOctalString(decimal)); } }
Output:
Enter a binary number: 101010 Octal: 52
Method 2: Using Division by 8
We convert binary to decimal and then repeatedly divide the decimal number by 8 to get the octal equivalent.
import java.util.Scanner; public class BinaryToOctalDivision { static int binaryToDecimal(int binary) { int decimal = 0, base = 1; while (binary > 0) { decimal += (binary % 10) * base; binary /= 10; base *= 2; } return decimal; } static String decimalToOctal(int decimal) { StringBuilder octal = new StringBuilder(); while (decimal > 0) { octal.insert(0, decimal % 8); decimal /= 8; } return octal.toString(); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a binary number: "); int binary = scanner.nextInt(); System.out.println("Octal: " + decimalToOctal(binaryToDecimal(binary))); } }
Output:
Enter a binary number: 101010 Octal: 52
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 BinaryToOctalRecursion { static int binaryToDecimalRecursive(int binary) { if (binary == 0) return 0; return (binary % 10) + 2 * binaryToDecimalRecursive(binary / 10); } static String decimalToOctalRecursive(int decimal) { if (decimal == 0) return ""; return decimalToOctalRecursive(decimal / 8) + (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); String octal = decimal != 0 ? decimalToOctalRecursive(decimal) : "0"; System.out.println("Octal: " + octal); } }
Output:
Enter a binary number: 101010 Octal: 52