[java] Convert hexadecimal string (hex) to a binary string

I found the following way hex to binary conversion:

String binAddr = Integer.toBinaryString(Integer.parseInt(hexAddr, 16)); 

While this approach works for small hex numbers, a hex number such as the following

A14AA1DBDB818F9759

Throws a NumberFormatException.

I therefore wrote the following method that seems to work:

private String hexToBin(String hex){
    String bin = "";
    String binFragment = "";
    int iHex;
    hex = hex.trim();
    hex = hex.replaceFirst("0x", "");

    for(int i = 0; i < hex.length(); i++){
        iHex = Integer.parseInt(""+hex.charAt(i),16);
        binFragment = Integer.toBinaryString(iHex);

        while(binFragment.length() < 4){
            binFragment = "0" + binFragment;
        }
        bin += binFragment;
    }
    return bin;
}

The above method basically takes each character in the Hex string and converts it to its binary equivalent pads it with zeros if necessary then joins it to the return value. Is this a proper way of performing a conversion? Or am I overlooking something that may cause my approach to fail?

Thanks in advance for any assistance.

This question is related to java binary hex

The answer is


public static byte[] hexToBin(String str)
    {
        int len = str.length();
        byte[] out = new byte[len / 2];
        int endIndx;

        for (int i = 0; i < len; i = i + 2)
        {
            endIndx = i + 2;
            if (endIndx > len)
                endIndx = len - 1;
            out[i / 2] = (byte) Integer.parseInt(str.substring(i, endIndx), 16);
        }
        return out;
    }

import java.util.*;
public class HexadeciamlToBinary
{
   public static void main()
   {
       Scanner sc=new Scanner(System.in);
       System.out.println("enter the hexadecimal number");
       String s=sc.nextLine();
       String p="";
       long n=0;
       int c=0;
       for(int i=s.length()-1;i>=0;i--)
       {
          if(s.charAt(i)=='A')
          {
             n=n+(long)(Math.pow(16,c)*10);
             c++;
          }
         else if(s.charAt(i)=='B')
         {
            n=n+(long)(Math.pow(16,c)*11);
            c++;
         }
        else if(s.charAt(i)=='C')
        {
            n=n+(long)(Math.pow(16,c)*12);
            c++;
        }
        else if(s.charAt(i)=='D')
        {
           n=n+(long)(Math.pow(16,c)*13);
           c++;
        }
        else if(s.charAt(i)=='E')
        {
            n=n+(long)(Math.pow(16,c)*14);
            c++;
        }
        else if(s.charAt(i)=='F')
        {
            n=n+(long)(Math.pow(16,c)*15);
            c++;
        }
        else
        {
            n=n+(long)Math.pow(16,c)*(long)s.charAt(i);
            c++;
        }
    }
    String s1="",k="";
    if(n>1)
    {
    while(n>0)
    {
        if(n%2==0)
        {
            k=k+"0";
            n=n/2;
        }
        else
        {
            k=k+"1";
            n=n/2;
        }
    }
    for(int i=0;i<k.length();i++)
    {
        s1=k.charAt(i)+s1;
    }
    System.out.println("The respective binary number is : "+s1);
    }
    else
    {
        System.out.println("The respective binary number is : "+n);
    }
  }
}

With all zeroes:

static String hexToBin(String s) {
    String preBin = new BigInteger(s, 16).toString(2);
    Integer length = preBin.length();
    if (length < 8) {
        for (int i = 0; i < 8 - length; i++) {
            preBin = "0" + preBin;
        }
    }
    return preBin;
}

Integer.parseInt(hex,16);    
System.out.print(Integer.toBinaryString(hex));

Parse hex(String) to integer with base 16 then convert it to Binary String using toBinaryString(int) method

example

int num = (Integer.parseInt("A2B", 16));
System.out.print(Integer.toBinaryString(num));

Will Print

101000101011

Max Hex vakue Handled by int is FFFFFFF

i.e. if FFFFFFF0 is passed ti will give error


public static byte[] hexToBytes(String string) {
 int length = string.length();
 byte[] data = new byte[length / 2];
 for (int i = 0; i < length; i += 2) {
  data[i / 2] = (byte)((Character.digit(string.charAt(i), 16) << 4) + Character.digit(string.charAt(i + 1), 16));
 }
 return data;
}

Fast, and works for large strings:

    private String hexToBin(String hex){
        hex = hex.replaceAll("0", "0000");
        hex = hex.replaceAll("1", "0001");
        hex = hex.replaceAll("2", "0010");
        hex = hex.replaceAll("3", "0011");
        hex = hex.replaceAll("4", "0100");
        hex = hex.replaceAll("5", "0101");
        hex = hex.replaceAll("6", "0110");
        hex = hex.replaceAll("7", "0111");
        hex = hex.replaceAll("8", "1000");
        hex = hex.replaceAll("9", "1001");
        hex = hex.replaceAll("A", "1010");
        hex = hex.replaceAll("B", "1011");
        hex = hex.replaceAll("C", "1100");
        hex = hex.replaceAll("D", "1101");
        hex = hex.replaceAll("E", "1110");
        hex = hex.replaceAll("F", "1111");
        return hex;
    }

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to binary

Difference between opening a file in binary vs text Remove 'b' character do in front of a string literal in Python 3 Save and retrieve image (binary) from SQL Server using Entity Framework 6 bad operand types for binary operator "&" java C++ - Decimal to binary converting Converting binary to decimal integer output How to convert string to binary? How to convert 'binary string' to normal string in Python3? Read and write to binary files in C? Convert to binary and keep leading zeros in Python

Examples related to hex

Transparent ARGB hex value How to convert a hex string to hex number Javascript: Unicode string to hex Converting Hexadecimal String to Decimal Integer Convert string to hex-string in C# Print a variable in hexadecimal in Python Convert ascii char[] to hexadecimal char[] in C Hex transparency in colors printf() formatting for hex Python Hexadecimal