hexadecimal to octal in java

Let’s learn hexadecimal to octal in java.

hexadecimal to octal in java

Let’s convert hexadecimal to octal.

For example: hexadecimal value – 2E5

binary value of 2 is 0010

binary value of E is 1110

binary value of 5 is 0101

Group in terms of three – 001011100101

001 011 100 101

Octal number is – 1345

Here’s the java program.

import java.util.Scanner;
public class HexadecimalToOctal
{
   public static void main(String[] args)
   {
      int decimalNumber, a = 1, b;
      int[] octalNumber = new int[100];
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter a hexadecimal number: ");
      String strHexNumber = sc.nextLine();
      // converting hexadecimal number to decimal number
      decimalNumber = hexToDecimal(strHexNumber);
      // converting decimal to octal
      while(decimalNumber != 0)
      {
         octalNumber[a++] = decimalNumber % 8;
         decimalNumber = decimalNumber / 8;
      }
      System.out.print("Octal number is: ");
      for(b = a - 1; b > 0; b--)
      {
         System.out.print(octalNumber[b]);
      }
      System.out.print("\n");
      sc.close();
   }
   public static int hexToDecimal(String str)
   {
      String strDigits = "0123456789ABCDEF";
      str = str.toUpperCase();
      int value = 0;
      for(int a = 0; a < str.length(); a++)
      {
         char ch = str.charAt(a);
         int deci = strDigits.indexOf(ch);
         value = 16 * value + deci;
      }
      return value;
   }
}


Output:

Please enter a hexadecimal number: 2E5
Octal number is: 1345


Also read – hexadecimal to decimal in java

Also read – octal to decimal in java