2

Considering the following String

String hexData = "1E01";

Is there a simple implementation to turn any hexData into a bit-based String array, like

String hexDataBits = "0001111000000001";

?

2
  • Why would "1E01" convert to "00001111000000001"? Did you mean "0001111000000001" Commented Mar 9, 2015 at 19:38
  • "0001111000000001"; fixed. Commented Mar 9, 2015 at 19:40

1 Answer 1

3

Here you go. Convert your hex string to an int value using the built in parseInt function, then turn that into a binary string.

public String hexToBinary(String hexBits) {
    int intversion = Integer.parseInt(hexBits, 16);
    String binaryVers = Integer.toBinaryString(intversion);
    return binaryVers;
}

Note that this is not padded. If you want to pad it, modify binaryVers.

eg:

// if you're dead set on having at least 16 chars, put this before the return statement
int padding = 16 - binaryVers.length();
while (padding > 0) {
    binaryVers = "0" + binaryVers;
    padding--;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, I was dead set on having 16 chars. Thank you sir!
@Machado Keep in mind that if the hex # gets large enough 16 chars may not be enough to contain it... in which case it won't be formatted to be exactly 16, and you'll get more than 16 characters.
i'll keep that in mind! But for now I assume there will be no problems, since the bit arrays won't pass this limit.

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.