octal to binary in java code example

Example 1: octal to binary in java

import java.util.Scanner;
public class OctalToBinaryJava
{
   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter octal number: ");
      int octal = Integer.parseInt(sc.nextLine(), 8);
      String strBinary = Integer.toBinaryString(octal);
      System.out.println("Binary value is: " + strBinary);
      sc.close();
   }
}

Example 2: binary to octal in java

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;
   }
}

Example 3: binary to octal in java

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);
   }
}

Tags:

Misc Example