English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input/Output (I/O)/O)

Java Reader/Writer

Java Other Topics

Java program for converting binary numbers to octal numbers and vice versa

Java Comprehensive Examples

In this program, you will learn to use functions in Java to convert binary numbers to octal numbers and vice versa.

Example1: Program to convert binary to octal

In this program, we will first convert the binary number to decimal. Then, the decimal number is converted to octal.

public class BinaryOctal {
    public static void main(String[] args) {
        long binary = 101001;
        int octal = convertBinarytoOctal(binary);
        System.out.printf("%d binary = %d octal", binary, octal);
    }
    public static int convertBinarytoOctal(long binaryNumber)
    {
        int octalNumber = 0, decimalNumber = 0, i = 0;
        while(binaryNumber != 0)
        {
            decimalNumber += (binaryNumber % 10) * Math.pow(2, i);
            ++;
            binaryNumber /= 10;
        }
        i = 1;
        while (decimalNumber != 0)
        {
            octalNumber +i = (decimalNumber % 8) * ;
            decimalNumber /= 8;
            i *= 10;
        }
        return octalNumber;
    }
}

When running the program, the output is:

101001 Binary = 51 Octal

This conversion occurs as follows:

Binary to decimal
1 * 25 + 0 * 24 + 1 * 23 + 0 * 22 + 0 * 21 + 1 * 20 = 41
Decimal to octal
8 | 418 | 5 -- 1
8 | 0 -- 5
(51)

Example2: Program to convert octal to binary

In this program, the octal number is first converted to decimal. Then, the decimal number is converted to binary.

public class OctalBinary {
    public static void main(String[] args) {
        int octal = 67;
        long binary = convertOctalToBinary(octal);
        System.out.printf("%d in octal = %d binary", octal, binary);
    }
    public static long convertOctalToBinary(int octalNumber)
    {
        int decimalNumber = 0, i = 0;
        long binaryNumber = 0;
        while(octalNumber != 0)
        {
            decimalNumber +=(octalNumber % 10) * Math.pow(8, i);
            ++;
            octalNumber/=10;
        }
        i = 1;
        while (decimalNumber != 0)
        {
            binaryNumber +i = (decimalNumber % 2) * ;
            decimalNumber /= 2;
            i *= 10;
        }
        return binaryNumber;
    }
}

When running the program, the output is:

67 in octal = 110111 Binary

This conversion occurs as follows:

Octal to Decimal
6 * 81 + 7 * 80 = 55
Decimal to Binary
2 | 552 | 27 -- 1
2 | 13 -- 1
2 | 6  -- 1
2 | 3  -- 0
2 | 1  -- 1
2 | 0  -- 1
(110111)

Java Comprehensive Examples