Convert hexadecimal string (hex) to a binary string

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

BigInteger.toString(radix) will do what you want. Just pass in a radix of 2.

static String hexToBin(String s) {
  return new BigInteger(s, 16).toString(2);
}

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

Tags:

Hex

Java

Binary