17

I would like to convert a hex string to a binary string. For example, Hex 2 is 0010. Below is the code:

String HexToBinary(String Hex)
{
    int i = Integer.parseInt(Hex);
    String Bin = Integer.toBinaryString(i);
    return Bin;
}

However this only works for Hex 0 - 9; it won't work for Hex A - F because it uses int. Can anyone enhance it?

1
  • just to let you (and other users) know, java convention states you should be starting from lower case for variable names. e.g. Hex, should be hex, and Bin, should be bin. Commented Aug 18, 2014 at 7:48

7 Answers 7

39

You need to tell Java that the int is in hex, like this:

String hexToBinary(String hex) {
    int i = Integer.parseInt(hex, 16);
    String bin = Integer.toBinaryString(i);
    return bin;
}
Sign up to request clarification or add additional context in comments.

2 Comments

will not wokr for a huge hex string value
@KaveeshKanwal This should come as no surprise, as OP uses integers, right?
22

the accepted version will only work for 32 bit numbers.

Here's a version that works for arbitrarily long hex strings:

public static String hexToBinary(String hex) {
    return new BigInteger(hex, 16).toString(2);
}

1 Comment

it's adding extra bits
7

The accepted answer only works for 32-bit values, and the alternate BigInteger version truncates leading zeros in the binary string! Here's a function that should work in all cases.

public static String hexToBinary(String hex) {
    int len = hex.length() * 4;
    String bin = new BigInteger(hex, 16).toString(2);

    //left pad the string result with 0s if converting to BigInteger removes them.
    if(bin.length() < len){
        int diff = len - bin.length();
        String pad = "";
        for(int i = 0; i < diff; ++i){
            pad = pad.concat("0");
        }
        bin = pad.concat(bin);
    }
    return bin;
}

1 Comment

it is adding extra bits
6

Here are some routines I wrote for manipulating hex, plaintext, and binary, hope they help. Since I borrowed ideas from these threads, thought I would share.

public static String zero_pad_bin_char(String bin_char){
    int len = bin_char.length();
    if(len == 8) return bin_char;
    String zero_pad = "0";
    for(int i=1;i<8-len;i++) zero_pad = zero_pad + "0"; 
    return zero_pad + bin_char;
}
public static String plaintext_to_binary(String pt){
    return hex_to_binary(plaintext_to_hex(pt));
}
public static String binary_to_plaintext(String bin){
    return hex_to_plaintext(binary_to_hex(bin));
}
public static String plaintext_to_hex(String pt) {
    String hex = "";
    for(int i=0;i<pt.length();i++){
        String hex_char = Integer.toHexString(pt.charAt(i));
        if(i==0) hex = hex_char;
        else hex = hex + hex_char;
    }
    return hex;  
}
public static String binary_to_hex(String binary) {
    String hex = "";
    String hex_char;
    int len = binary.length()/8;
    for(int i=0;i<len;i++){
        String bin_char = binary.substring(8*i,8*i+8);
        int conv_int = Integer.parseInt(bin_char,2);
        hex_char = Integer.toHexString(conv_int);
        if(i==0) hex = hex_char;
        else hex = hex+hex_char;
    }
    return hex;
}
public static String hex_to_binary(String hex) {
    String hex_char,bin_char,binary;
    binary = "";
    int len = hex.length()/2;
    for(int i=0;i<len;i++){
        hex_char = hex.substring(2*i,2*i+2);
        int conv_int = Integer.parseInt(hex_char,16);
        bin_char = Integer.toBinaryString(conv_int);
        bin_char = zero_pad_bin_char(bin_char);
        if(i==0) binary = bin_char; 
        else binary = binary+bin_char;
        //out.printf("%s %s\n", hex_char,bin_char);
    }
    return binary;
}
public static String hex_to_plaintext(String hex) {
    String hex_char;
    StringBuilder plaintext = new StringBuilder();
    char pt_char;
    int len = hex.length()/2;
    for(int i=0;i<len;i++){
        hex_char = hex.substring(2*i,2*i+2);
        pt_char = (char)Integer.parseInt(hex_char,16);
        plaintext.append(pt_char);
        //out.printf("%s %s\n", hex_char,bin_char);
    }
    return plaintext.toString();
}

}

Comments

5

You need to use the other Integer.parseInt() method.

Integer.parseInt(hex, 16);

1 Comment

This returned a hexidecimal integer and threw a number format when I tried converting it to binary using Integer.toBinaryString(Integer.parseInt(hex, 16));
4
private static Map<String, String> digiMap = new HashMap<>();

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

static String hexToBin(String s) {
    char[] hex = s.toCharArray();
    String binaryString = "";
    for (char h : hex) {
        binaryString = binaryString + digiMap.get(String.valueOf(h));
    }
    return binaryString;
}

Sorry, it's been a little bit late. But still, I think my answer is the most straight forward and simple one.

Comments

0
public static String hexToBits(String s) {
    if (s == null || s.length()==0) return "";
    String ret = new BigInteger(s, 16).toString(2);
    int totalLength = s.length() * 4;
    while (totalLength - ret.length() > 0) {
        ret = "0" + ret;
    }
    return ret;
}

1 Comment

BTW the String class has a repeat method (replacement for the while loop, since Java 11)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.