如何将十六进制字符串转换为字节数组?

时间:2012-07-15 08:53:28

标签: java

  

可能重复:
  Convert a string representation of a hex dump to a byte array using Java?

我正在尝试将十六进制字符串“FFFFFFFFFFFFFFF”转换为大小为8的字节数组

结果应该是

byte[] mKey =  { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
        (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF };

我尝试了for循环

public static byte[] HexString2Bytes(String src) {
    byte[] res = new byte[8];
    for (int i = 0; i < 16; i = i + 2) {
        res[i] = convertToByte(src.substring(i, i + 2));
    }
    return res;
}

问题是,我不知道如何实现convertToByte()方法转换十六进制字符串,如“FF”到0xFF,请帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

int convertToByte(String s){
    return Integer.parseString(s, 16);
}
相关问题