如何将string转换为byte

如何将string转换为byte

问题描述:

开发中需要这样的功能,将String str = "0f8adffb11dc" 转换为byte[] byteText = { 0x0f, 0x8a, 0xdf, 0xfb,0x11, 0xdc};请问如何实现,谢谢!

 public class Test {
    public static byte uniteBytes(byte src0, byte src1) { 
        byte _b0 = Byte.decode("0x" + new String(new byte[]{src0})).byteValue(); 
        _b0 = (byte)(_b0 << 4); 
        byte _b1 = Byte.decode("0x" + new String(new byte[]{src1})).byteValue(); 
        byte ret = (byte)(_b0 ^ _b1); 
        return ret; 
    } 
    public static byte[] HexString2Bytes(String src){ 
        byte[] ret = new byte[src.length()/2]; 
        byte[] tmp = src.getBytes(); 
        for(int i=0; i<src.length()/2; i++){ 
            ret[i] = uniteBytes(tmp[i*2], tmp[i*2+1]); 
        } 
        return ret; 
    } 
    public static void main(String[] args) {
        byte[] byteText = { 0x0f, (byte) 0x8a, (byte) 0xdf, (byte) 0xfb,0x11, (byte) 0xdc};
        byte[] ret = Test.HexString2Bytes("0f8adffb11dc");
    }
}

String str = "0f8adffb11dc";
byte[] result = new byte[str.length() / 2];
for (int i = 0; i < str.length(); i += 2)
{
result[i / 2] = Byte.parse(str.subString(i, 2), 16);
}

两位字符串一组截取,然后转换成十六进制数据。

string str = "0f8adffb11dc";
byte[] resultList = new byte[str.Length / 2];
for (int i = 0; i < str.Length / 2; i++)
{
resultList[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
}