hexadecimal to binary in java

Let’s learn hexadecimal to binary in java.

hexadecimal to binary in java

Here’s the java program.

import java.util.Scanner;
public class HexadecimalToBinaryJava
{
   public static void main(String[] args)
   {
      int decimalNumber, a = 1, b;
      int[] binaryNumber = new int[100];
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter hexadecimal number: ");
      String hexaDecimalNumber = sc.nextLine();
      // converting hexadecimal to decimal number
      decimalNumber = toDecimal(hexaDecimalNumber);
      // converting decimal number to binary number
      while(decimalNumber != 0)
      {
         binaryNumber[a++] = decimalNumber % 2;
         decimalNumber = decimalNumber / 2;
      }
      System.out.print("The equivalent binary number is: ");
      for(b = a - 1; b > 0; b--)
      {
         System.out.print(binaryNumber[b]);
      }
      System.out.print("\n");
      sc.close();
   }
   public static int toDecimal(String str)
   {
      String strDigits = "0123456789ABCDEF";
      str = str.toUpperCase();
      int val = 0;
      for(int a = 0; a < str.length(); a++)
      {
         char c = str.charAt(a);
         int d = strDigits.indexOf(c);
         val = 16 * val + d;
      }
      return val;
   }
}


Output:

Please enter hexadecimal number: 2A6
The equivalent binary number is: 1010100110

Please enter hexadecimal number: 2B4
The equivalent binary number is: 1010110100


Also read – hexadecimal to octal in java

Also read – hexadecimal to decimal java

Also read – decimal to binary java