简体   繁体   中英

Convert a hex string (byte list) to a byte array

I want to convert a string ("00812B1FA4BEA310199D6E00DD010F5402000001807") to a byte array. But I want each digit of the string to be the hex value.

Expected result:

array[0] = 0x00;

array[1] = 0x81;

array[0] = 0x2B;

array[0] = 0x1F;

etc...

I tried several methods. None gave the expected result. The closest ones were:

private static byte[] Convert(string tt)
{
    byte[] bytes2 = new byte[tt.Length];
    int i = 0;
    foreach ( char c in tt)
    {
        bytes2[i++] = (byte)((int)c - 48);
    }
    return bytes2;
}

public static byte[] ConvertHexStringToByteArray(string hexString)
{

    byte[] HexAsBytes = new byte[hexString.Length / 2];
    for (int index = 0; index < HexAsBytes.Length; index++)
    {
        string byteValue = hexString.Substring(index * 2, 2);
        byte[] a =  GetBytes(byteValue);
        HexAsBytes[index] = a[0];
    }
    return HexAsBytes;
}

You can use Convert.ToByte to convert 2 hexadecimal chars to byte.

public static byte[] HexToByteArray(string hexstring)
{
    var bytes = new List<byte>();

    for (int i = 0; i < hexstring.Length/2; i++)
        bytes.Add(Convert.ToByte("" + hexstring[i*2] + hexstring[i*2 + 1], 16));

    return bytes.ToArray();
}

Found solution here: How do you convert Byte Array to Hexadecimal String, and vice versa? ( answer starting by Inverse function for Waleed Eissa code) Difficult to find because the thread has 36 answers.

 public static byte[] HexToBytes(string hexString)
    {
        byte[] b = new byte[hexString.Length / 2];
        char c;
        for (int i = 0; i < hexString.Length / 2; i++)
        {
            c = hexString[i * 2];
            b[i] = (byte)((c < 0x40 ? c - 0x30 : (c < 0x47 ? c - 0x37 : c - 0x57)) << 4);
            c = hexString[i * 2 + 1];
            b[i] += (byte)(c < 0x40 ? c - 0x30 : (c < 0x47 ? c - 0x37 : c - 0x57));
        }

        return b;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM