Convert Binary to Octal in Java

Exercise:

Write a Java Program to convert Binary number to octal number.

Click Here to View the Solution!
 public class BinaryToOctal {
  
     public static void main(String[] args) {
         long binary = 111011001;
         int octal = convertBinarytoOctal(binary);
         System.out.printf("%d in binary = %d in 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);
             ++i;
             binaryNumber /= 10;
         }
  
         i = 1;
  
         while (decimalNumber != 0)
         {
             octalNumber += (decimalNumber % 8) * i;
             decimalNumber /= 8;
             i *= 10;
         }
  
         return octalNumber;
     }
 } 
Click Here to View the Output!
1110110010 in binary = 1662 in octal
Click Here to View the Explanation!
  • This program calculates the Octal equivalent for a given Binary number by employing covertBinaryToOctal() function.
  • Firstly, a long integer 1110110010 is declared in the main function, later passed as an argument to the function.
  • The argument value is held by the parameter ‘binaryNumber’ of the function.
  • The program keeps recurring till the values of ‘binaryNumber’ and ‘decimalNumber’ do not equal ‘0’ during both ‘while’ conditions respectively.
  • The reason for two segments of the program is that the binary number has to be converted to the decimal equivalent first; only then the decimal number is converted into octal number.
  • During first iteration of first ‘while’ condition (here value of ‘i’ is ‘0’ initially), the product of remainder of the binary number ‘1110110010’ to the base ‘10’ and exponential value of ‘20 =1’ initially, is added to the value of ‘decimalNumber’ variable. (1 * 20 = 1)
  • The loop will be executed until the calibrated value of ‘162’ is returned, by the second ‘while’ condition, as an octal equivalent for binary number 1110110010
%d bloggers like this: