Ankit Tater
Ankit Tater

Reputation: 619

How to convert Hex String to binary string with leading zeros?

Suppose I have a hex String as 0F0A. I need the output as 0000111100001010. I tried the following method but this returns 111100001010 - I need the leading 0000 as well.

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

Upvotes: 2

Views: 1781

Answers (2)

you are almost there... just need to format it:

   String string = "0f0a";
   String value = new BigInteger(string, 16).toString(2);
   String formatPad = "%" + (string.length() * 4) + "s";
   System.out.println(String.format(formatPad, value).replace(" ", "0"));

the formatPad is the padder (4 bit for each hex symbol)... in your case 16

Upvotes: 3

Anukul Mittal
Anukul Mittal

Reputation: 29

Try this code:

String hexToBinary(String hexString) {
    int i = Integer.parseInt(hexString, 16);
    String binaryString = Integer.toBinaryString(i);
    String padded = String.format("%8s", Integer.toBinaryString(i)).replace(' ', '0') 
    return padded;
}

Upvotes: -1

Related Questions