[英]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. 我很难尝试将包含某些字节的十六进制表示的String转换为其对应的字节数组。
I am getting 32bytes using the following code: 我使用以下代码获得32字节:
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? 知道如何从String到数组吗? In other words, how to do the reverse of the code above.
换句话说,如何反转上面的代码。
Thanks. 谢谢。
I'd try commons-codec byte[] originalBytes = Hex.decodeHex(string.toCharArray())
. 我会尝试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. 您可以使用Integer.parseInt(String s,int radix)方法将十六进制表示形式转换回整数,然后可以将其转换为字节。 Use that to process the string two characters at a time.
用它来一次处理字符串两个字符。
Use the 使用
String.getBytes();
method 方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.