Java 如何将十六进制字符串转换为(十六进制)字节

Java 如何将十六进制字符串转换为(十六进制)字节,java,hex,Java,Hex,我得到了一个类似“0xFF”的十六进制字符串,并希望将该字符串转换为字节0xFF,因为另一个函数需要该值作为十六进制字节。比如说: String hexstring="0xFF"; //convert to byte byte hexbyte = (byte) 0xFF; 感谢您的帮助(字节)(Integer.parseInt(“ef”,16)和0xff)将适用于您公共静态字节[]asByteArray(字符串十六进制){ public s

我得到了一个类似“0xFF”的十六进制字符串,并希望将该字符串转换为字节0xFF,因为另一个函数需要该值作为十六进制字节。比如说:

         String hexstring="0xFF";
         //convert to byte
         byte hexbyte = (byte) 0xFF;
感谢您的帮助(字节)(Integer.parseInt(“ef”,16)和0xff)将适用于您

公共静态字节[]asByteArray(字符串十六进制){
public static byte[] asByteArray(String hex) {
    // Create a byte array half the length of the string.
    byte[] bytes = new byte[hex.length() / 2];

    // Repeat the process for the number of elements in the byte array.
    for (int index = 0; index < bytes.length; index++) {
        // Convert hexadecimal string to bytes and store in array.
        bytes[index] =
            (byte) Integer.parseInt(
                hex.substring(index * 2, (index + 1) * 2),
                16);
    }

    // return byte array。
    return bytes;
}
//创建一个长度为字符串一半的字节数组。 byte[]bytes=新字节[hex.length()/2]; //对字节数组中的元素数重复此过程。 for(int index=0;index
我的问题可能重复的不是如何转换为十进制字节,而是如何转换为十六进制字节。所以你的代码给了我一个小数,我需要一个十六进制字节。