Algorithm


Binary to Octal Conversion Algorithm:

  1. Accept a binary number as input.
  2. Validate the input to ensure it contains only 0s and 1s.
  3. Group the binary digits into sets of three starting from the rightmost side.
  4. If the leftmost group has fewer than three digits, pad it with leading zeros.
  5. Convert each group of three binary digits to its decimal equivalent.
  6. Map the decimal values to their corresponding octal digits (0-7).
  7. Concatenate the octal digits to get the final octal representation.

Octal to Binary Conversion Algorithm:

  1. Accept an octal number as input.
  2. Validate the input to ensure it contains only digits 0-7.
  3. Convert each octal digit to its binary equivalent (3 binary digits for each octal digit).
  4. Concatenate the binary equivalents to get the final binary representation.

 

Code Examples

#1 Code Example- Program to Convert Binary to Octal

Code - Java Programming

class Main {
  public static void main(String[] args) {
    long binary = 101001;
    int octal = convertBinarytoOctal(binary);
    System.out.println(binary + " in binary = " + octal + " in octal");
  }

  public static int convertBinarytoOctal(long binaryNumber) {
    int octalNumber = 0, decimalNumber = 0, i = 0;

    while (binaryNumber != 0) {
      decimalNumber += (binaryNumber % 10) * Math.pow(2, i);
      ++i;
      binaryNumber /= 10;
    }

    i = 1;

    while (decimalNumber != 0) {
      octalNumber += (decimalNumber % 8) * i;
      decimalNumber /= 8;
      i *= 10;
    }

    return octalNumber;
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
101001 in binary = 51 in octal

#2 Code Example- Program to Convert Octal to Binary

Code - Java Programming

class Main {
  public static void main(String[] args) {
    int octal = 67;
    long binary = convertOctalToBinary(octal);
    System.out.println(octal + " in octal = " + binary + " in 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);
      ++i;
      octalNumber /= 10;
    }

    i = 1;

    while (decimalNumber != 0) {
      binaryNumber += (decimalNumber % 2) * i;
      decimalNumber /= 2;
      i *= 10;
    }

    return binaryNumber;
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
67 in octal = 110111 in binary
Advertisements

Demonstration


Java Programing Example to Convert Binary Number to Octal and vice-versa-DevsEnv