Binary to octal in java

Let’s learn binary to octal in java.

Binary to octal in java

Binary to octal conversion in java is one of the frequently asked interview question.

A binary number system with base-2 comprises of two digits zero and one (0’s and 1’s). While octal number is with base-8 comprises of digits from 0 to 7.

In this post we are going to see two ways to convert binary number to octal number. First convert binary number to decimal number and then convert to octal number. Second using toOctalString() method which is a built-in method in java.


1st way: In the below java program first convert binary number to decimal number. After converting to decimal number, using while loop, loop until decimal number becomes 0.

In every iteration in while loop get remainder by dividing decimal number by 8. Now multiply this remainder with increasing power of 10. Lastly divide given number by 8. Here’s program to convert binary to octal.

public class BinaryToOctal
{
   public static void main(String[] args) 
   {
      BinaryToOctal obj = new BinaryToOctal();
      System.out.println(obj.convertToOctal(1001100001));
   }
   int convertToDecimal(long binary)
   {
      int decimal = 0, a = 0;
      while(binary > 0)
      {
         decimal += Math.pow(2, a++) * (binary % 10);
         binary /= 10;
      }
      return decimal;
   }
   int convertToOctal(long binary)
   {
      int octal = 0, a = 0;
      int decimalNumber = convertToDecimal(binary);
      while(decimalNumber != 0)
      {
         octal += (decimalNumber % 8) * ((int)Math.pow(10, a++));
         decimalNumber /= 8;
      }
      return octal;
   }
}


Output:

1141


2nd way: We can also use Integer.toOctalString() method to convert binary to octal. toOctalString() method returns the string representation of the unsigned integer value represented by the argument in octal (base 8).

Now let’s see an example.

public class UsingtoOctalStringMethod
{
   public static void main(String[] args)
   {
      String strNumber = "1001001100001";
      int binary = Integer.parseInt(strNumber, 2);
      String strOctal = Integer.toOctalString(binary);
      System.out.println("Octal value is: " + strOctal);
   }
}


Output:

Octal value is: 11141


Also read – java overview