nunos
nunos

Reputation: 21389

Convert the hexadecimal string representation of some bytes into a byte array in Java

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.

Upvotes: 1

Views: 1148

Answers (3)

Esko Luontola
Esko Luontola

Reputation: 73625

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.

Upvotes: 1

Bozho
Bozho

Reputation: 597106

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

Upvotes: 4

katsharp
katsharp

Reputation: 2551

Use the

String.getBytes();

method

Upvotes: -1

Related Questions