Octal to binary conversion using Java

Octal to binary conversion using Java :

Here, in this page we will discuss octal to binary conversion using java. For this purpose we need to ask a octal number from user and convert that octal number to its binary equivalent form and then print the converted number on to the screen.
For conversion, we first convert the octal number into decimal form and then convert the decimal number to binary number. For better understanding with an example just have a look towards the diagram shown at the right.
Octal to binary conversion using java

Working :

Step 1 : Ask the user to enter an octal number.

[Logic for conversion from octal number to decimal number]

Step 2 : Declare two variables, one for storing decimal value and second for storing value of the power.

Step 3 : Use  the while loop till octal number entered by user is greater than 0.

Step 4 : Use a statement to get the last digit of the octal number.

Step 5 : Use the statement for adding each digit by multiplying by the power of 8 and power starts with 0 till p-1 (where p is the number of digits in the octal number) by using power function.

Step 6 : Use the statement for removing last digit of the octal number and taking only remaining number and increase the value of the power by 1.

Step 7 : Repeat the steps 3 to 6 till the value of the loop does not gets false. 

[Logic for conversion from decimal number to binary number]

Step 8 : Now declare an array and a variable for pointing index value of the array.

Step 9 : Use  the while loop till the converted decimal number is greater than 0.

Step 10 : Divide the decimal number by 2 and store the remainder in the array and update the decimal number with the quotient.

Step 11 : Repeat the steps 9 and 10 till the decimal number is greater than 0.

Step 12 : Print the array in reverse order.

Octal to binary conversion using java

Code in Java :

//Java program to convert octal number to binary number
import java.util.Scanner;
public class Octal_To_Binary
public static void main(String args[])
//scanner class object creation
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a octal number : ");
int octal = sc.nextInt();
//Declaring variable to store decimal number
int decimal = 0;
//Declaring variable to use in power
int n = 0;
//writing logic for the octal to decimal conversion
while(octal > 0)
int temp = octal % 10;
decimal += temp * Math.pow(8, n);
octal = octal/10;
int binary[] = new int[20];
int i = 0;
//writing logic for the decimal to binary conversion
while(decimal > 0)
int r = decimal % 2;
binary[i++] = r;
decimal = decimal/2;
//printing result
System.out.print("Binary number : ");
for(int j = i-1 ; j >= 0 ; j--)
System.out.print(binary[j]+" ");
//closing scanner class(not compulsory, but good practice)

Output :

Enter a octal number : 216
Binary number : 1 0 0 0 1 1 1 0