Write a program to convert Octal to Binary number system


The program first declares an integer variable oct and initializes it to 14. This is the octal number that will be converted to binary. The program then prints the octal number.

Next, the program enters a loop that performs octal to decimal conversion. It uses the modulo operator % to obtain the rightmost digit of the octal number oct and stores it in the variable temp. It then updates the decimal equivalent dec by adding temp multiplied by 8 raised to the power of n, where n is the position of the digit within the octal number. The loop continues until the octal number becomes 0.

After the loop, the program initializes an integer array bin of size 20 to store the binary digits. It also initializes variables i and r to 0. Then, the program enters another loop that performs decimal to binary conversion. It uses the modulo operator % to obtain the remainder of division of the decimal equivalent dec by 2, and stores it in the bin array at index i. It then updates the index i and the decimal equivalent dec by dividing it by 2. The loop continues until the decimal equivalent becomes 0.

Finally, the program prints the binary equivalent of the octal number by iterating over the bin array in reverse order starting from index i-1, which is the last index used to store a digit. For each digit, it prints it using System.out.print(). Note that there is no space or newline character between the digits, so they will be printed together as a single binary number.

Source Code

class Octal_Binary
{
    public static void main(String args[])
    {
        int oct = 14;		
        System.out.println("Octal number : "+oct);
        int dec = 0,n = 0;
        while(oct > 0)
        {
            int temp = oct % 10;
            dec += temp * Math.pow(8, n);
            oct = oct/10;
            n++;
        }
        int bin[] = new int[20];
        int i = 0;
        while(dec > 0)
        {
            int r = dec % 2;
            bin[i++] = r;
            dec = dec/2;
        }
        System.out.print("Binary number : ");
        for(int j = i-1 ; j >= 0 ; j--)
            System.out.print(bin[j]+"");
 
    }
} 

Output

Octal number : 14
Binary number : 1100

Example Programs