1

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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CloudAnywhere
  • 669
  • 1
  • 11
  • 27
  • Simple google search will give you few solutions that any one of them is working. – Orel Eraki Jan 27 '16 at 21:14
  • for those who are writing simple google search will give you solution... make the search and if it works publish the keywords that were used. I'm googling since a couple of hours for a solution that works. – CloudAnywhere Jan 27 '16 at 22:10
  • I've already did the search, found few matches, tested them. I also fixed your code, that only needed 2 simple minor fixes, but still, i would vote this as a duplicate. Simple `byte a = System.Convert.ToByte(byteValue, 16); HexAsBytes[index] = a;` – Orel Eraki Jan 27 '16 at 22:55

2 Answers2

0

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();
}
TSnake41
  • 405
  • 3
  • 8
0

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;
    }
Community
  • 1
  • 1
CloudAnywhere
  • 669
  • 1
  • 11
  • 27