Binary to octal conversion using Java

Binary to octal conversion using java :

 

In this article we will create a java program for converting a binary number to octal number. For this purpose we need to ask a binary number from user and convert that binary number to its octal equivalent form and then print the converted number on to the screen.
 
For conversion, we first convert the binary number into decimal form and then convert the decimal number to octal number. For better understanding with an example just have a look towards the diagram shown at the right.
Binary to octal conversion using Java

Working :

Step 1 : Ask the user to enter a binary number.

[Logic for conversion from binary 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 binary number entered by user is greater than 0.

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

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

Step 6 : Use the statement for removing last digit of the binary 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 get false. 

[Logic for conversion from decimal number to octal number]

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

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

Step 10 : Divide the decimal number by 8 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.

Code in Java :

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

Output :

Enter a binary number : 101010
Octal number : 52