convert hexadecimal to binary java code example

Example 1: hexadecimal to binary in java

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

Example 2: java convert hex to binary method

/**
 * Method receives String hexadecimal value and returns a String of a binary representation
 * hexadecimal string format (ex.:"2FFA")
 * Only works with positive hexadecimal values (16xF does not work)
 * Uses 2 for loops (hex -> dec & dec -> bin)
 */
private static int[] parseHexBinary(String hex) {
		String digits = "0123456789ABCDEF";
		int[] binaryValue = new int[hex.length()*4];
		long val = 0;
		
		// convert hex to decimal
		for(int i = 0; i < hex.length(); i++) {
			char c = hex.charAt(i);
			int d = digits.indexOf(c);
			val = val*16 + d;
		}
		
		// convert decimal to binary
		for(int i = 0; i < binaryValue.length; i++) {
			
			binaryValue[i] = (int) (val%2);
			val = val/2;
		}
		
		return binaryValue;
	}

Tags:

Java Example