string to binary and hexadecimal java code example

Example 1: java convert hex to binary method

/**
 * Method receives String hexadecimal value (of any range) and returns a String of a binary representation
 * hexadecimal string format (ex.:"2FFA")
 * Use of if-than-else statement inside for loop
 * Use the Integer.toBinaryString(int i) method
 */
private String parseHexBinary(String hex) {
		String digits = "0123456789ABCDEF";
  		hex = hex.toUpperCase();
		String binaryString = "";
		
		for(int i = 0; i < hex.length(); i++) {
			char c = hex.charAt(i);
			int d = digits.indexOf(c);
			if(d == 0)	binaryString += "0000"; 
			else  binaryString += Integer.toBinaryString(d);
		}
		return binaryString;
	}

Example 2: 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;
   }
}

Tags:

Java Example