2

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

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

And what if he doesn't know beforehand how long his input string is?
OK, thanks for demonstrating it. I don't think beginners always realize they can compute a format string. I strongly suggest you put string.length() * 4 in parentheses. Since the + is string concatenation and * is arithmetic multiplication, you really shouldn't combine the two types in the same expression without parentheses; I've seen things like String1 + number + 1 or String1 + number - 1 too often, which doesn't work. Yours will work due to operator precedence, but it's a bit confusing without the parens.
-1

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

1 Comment

And if his input is too large to fit in an Integer? The OP didn't say anything about how long his input string could be. And your code will not give him the output he wants on the input he specified--did you try it?

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.