简体   繁体   English

将一些字节的十六进制字符串表示形式转换为Java中的字节数组

[英]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.

相关问题 在java中将字节的字符串表示形式转换为字节[] - Convert String representation of bytes to byte[] in java 将十六进制字节数组的字符串表示形式转换为 Java 中的非 ascii 字符的字符串 - Convert string representation of a hexadecimal byte array to a string with non ascii characters in Java Java:将十六进制编码的字符串转换为十六进制字节 - Java: Convert a hexadecimal encoded String to a hexadecimal byte 使用 Java 将十六进制转储的字符串表示形式转换为字节数组? - Convert a string representation of a hex dump to a byte array using Java? 如何在Java中将字节数组转换为String,并跳过所有空字节? - How to convert a byte array to a String in Java, and skip all null bytes? 如何将二进制字符串转换为java中2字节的字节数组 - How to convert binary string to the byte array of 2 bytes in java 如何在Java中将字符串的二进制表示转换为字节? - How to convert a binary representation of a string into byte in Java? 有没有更简单的方法将字节数组转换为2字节大小的十六进制字符串? - Is there a simpler way to convert a byte array to a 2-byte-size hexadecimal string? 我如何在java中将java字节数组转换为十六进制数组 - How can i convert java byte array to hexadecimal array in java 将字节数组转换为等效字节数的字符串 - Convert byte array to string with equivalent number of bytes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM