Write a Java program to convert binary to octal. In this language, to convert binary, we first have to convert it to a decimal number and then to octal. So, we use parseInt to convert it to decimal and then use toOctalString for octal conversion.
package Remaining; public class BinaryToOctal1 { public static void main(String[] args) { String s1 = "1101"; String s2 = "11111"; String s3 = "101010"; int a = Integer.parseInt(s1, 2); int b = Integer.parseInt(s2, 2); int c = Integer.parseInt(s3, 2); System.out.println("Binary To Octal Result"); System.out.println(Integer.toOctalString(a)); System.out.println(Integer.toOctalString(b)); System.out.println(Integer.toOctalString(c)); } }
Binary To Octal Result
15
37
52
This Java example accepts the binary and converts it to octal using parseInt and toOctalString.
package Remaining; import java.util.Scanner; public class BinaryToOctal2 { private static Scanner sc; public static void main(String[] args) { sc= new Scanner(System.in); System.out.print("Please Enter Binary Number = "); String binary = sc.nextLine(); int decimalVal = Integer.parseInt(binary, 2); String OctalVal = Integer.toOctalString(decimalVal); System.out.println("Binary To Octal Result = " + OctalVal); } }
Java program to convert binary to octal using a while loop. The first while loop is to convert binary to decimal, and the second is to convert decimal to octal.
package Remaining; import java.util.Scanner; public class BinaryToOctal3 { private static Scanner sc; public static void main(String[] args) { sc= new Scanner(System.in); System.out.print("Please Enter Number = "); long binary = sc.nextLong(); int octalVal = 0, decimalVal = 0, i = 0, j = 0; while(binary > 0) { decimalVal = (int) (decimalVal + Math.pow(2, i++) * (binary % 10)); binary = binary / 10; } while(decimalVal != 0) { octalVal = (int) (octalVal + (decimalVal % 8) * Math.pow(10, j++)); decimalVal = decimalVal / 8; } System.out.println("Result = " + octalVal); } }
Please Enter Number = 11111111
Result = 377
Please Enter Number = 1101
Result = 15
This program helps to convert binary to octal using the for loop.
package Remaining; import java.util.Scanner; public class BinaryToOctal4 { private static Scanner sc; public static void main(String[] args) { sc= new Scanner(System.in); System.out.print("Please Enter Number = "); long binary = sc.nextLong(); int i, octalVal = 0, decimalVal = 0; for(i = 1; binary != 0; binary = binary / 10, i = i * 2) { decimalVal = (int) (decimalVal + (binary % 10) * i); } for(i = 1; decimalVal != 0; i = i * 10) { octalVal = octalVal + (decimalVal % 8) * i; decimalVal = decimalVal / 8; } System.out.println("Result = " + octalVal); } }
Please Enter Number = 11001101
Result = 315
Please Enter Number = 10101010
Result = 252