hexadecimal to octal in java

Solutions on MaxInterview for hexadecimal to octal in java by the best coders in the world

showing results for - "hexadecimal to octal in java"
Evan
16 Feb 2016
1import java.util.Scanner;
2public class OctalToHexadecimal
3{
4   public static void main(String[] args)
5   {
6      String strOctalNumber, strHexNumber;
7      Scanner sc = new Scanner(System.in);
8      System.out.print("Please enter octal number: ");
9      strOctalNumber = sc.nextLine();
10      int decimalNumber = Integer.parseInt(strOctalNumber, 8);
11      strHexNumber = Integer.toHexString(decimalNumber);
12      System.out.print("Hexadecimal value of " + strOctalNumber + " is: \n");
13      System.out.print(strHexNumber);
14      sc.close();
15   }
16}
Ashley
01 Sep 2020
1import java.util.Scanner;
2public class HexadecimalToOctal
3{
4   public static void main(String[] args)
5   {
6      int decimalNumber, a = 1, b;
7      int[] octalNumber = new int[100];
8      Scanner sc = new Scanner(System.in);
9      System.out.print("Please enter a hexadecimal number: ");
10      String strHexNumber = sc.nextLine();
11      // converting hexadecimal number to decimal number
12      decimalNumber = hexToDecimal(strHexNumber);
13      // converting decimal to octal
14      while(decimalNumber != 0)
15      {
16         octalNumber[a++] = decimalNumber % 8;
17         decimalNumber = decimalNumber / 8;
18      }
19      System.out.print("Octal number is: ");
20      for(b = a - 1; b > 0; b--)
21      {
22         System.out.print(octalNumber[b]);
23      }
24      System.out.print("\n");
25      sc.close();
26   }
27   public static int hexToDecimal(String str)
28   {
29      String strDigits = "0123456789ABCDEF";
30      str = str.toUpperCase();
31      int value = 0;
32      for(int a = 0; a < str.length(); a++)
33      {
34         char ch = str.charAt(a);
35         int deci = strDigits.indexOf(ch);
36         value = 16 * value + deci;
37      }
38      return value;
39   }
40}