javastring

Convert hex string to binary string


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?


Solution

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