1

I am having a hard time trying to convert a String containing the hexadecimal representation of some bytes to its corresponding byte array.

I am getting 32bytes using the following code:

StringBuffer sb = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++) {
    sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();

Any idea how to get from the String to the array? In other words, how to do the reverse of the code above.

Thanks.

3 Answers 3

4

I'd try commons-codec byte[] originalBytes = Hex.decodeHex(string.toCharArray()). In fact I would use it also for the encoding part.

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

Comments

1

You can use the Integer.parseInt(String s, int radix) method to convert the hexadecimal representation back to an integer, which you can then cast into a byte. Use that to process the string two characters at a time.

Comments

-1

Use the

String.getBytes();

method

1 Comment

this will give byte array conversion of the already byte representation of the String which will be very different from the original intended Hex.

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.