0

How can I convert a Hex String into 32bit Binary String? I did

String binAddr = Integer.toBinaryString(Integer.parseInt(hexAddr, 16));

To get the Binary String, but I need to pad it with 0's to ensure its 32 bits, how can I do that, preferably with Formatter?

1

1 Answer 1

0
String binAddr = Integer.toBinaryString(Integer.parseInt(hexAddr, 16)); 
String.format("%032", new BigInteger(binAddr));

The idea here is to parse the string back in as a decimal number temporarily (one that just so happens to consist of all 1's and 0's) and then use String.format().

Note that you basically have to use BigInteger, because binary strings quickly overflow Integer and Long resulting in NumberFormatExceptions if you try to use Integer.fromString() or Long.fromString().

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

Comments

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.