binary to octal in java

Let’s learn binary to octal in java.

binary to octal in java

Program to convert binary to octal is one of the frequently asked interview question.

Here’s the java program.

public class BinaryToOctal
{
   public static void main(String[] args)
   {
      long binaryNumber = 1010111;
      int octalNumber = convertToOctal(binaryNumber);
      System.out.println(binaryNumber + " in binary is equal to " + octalNumber + " in octal.");
   }
   public static int convertToOctal(long binaryNumber)
   {
      int octal = 0, decimal = 0, a = 0;
      while(binaryNumber != 0)
      {
         decimal += (binaryNumber % 10) * Math.pow(2, a);
         ++a;
         binaryNumber /= 10;
      }
      a = 1;
      while(decimal != 0)
      {
         octal += (decimal % 8) * a;
         decimal /= 8;
         a *= 10;
      }
      return octal;
   }
}


Output:

1010111 in binary is equal to 127 in octal.


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 = "100101";
      int binary = Integer.parseInt(strNumber, 2);
      String strOctal = Integer.toOctalString(binary);
      System.out.println("Octal value is: " + strOctal);
   }
}


Output:

Octal value is: 45


Also read – java overview