开发者

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

开发者 https://www.devze.com 2023-02-19 08:45 出处:网络
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 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.


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


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.


Use the

String.getBytes();

method

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号