/// <summary> /// Creates a byte array from the hexadecimal string. Each two characters are combined /// to create one byte. First two hexadecimal characters become first byte in returned array. /// Non-hexadecimal characters are ignored. /// </summary> /// <param name="hexString">string to convert to byte array</param> /// <param name="discarded">number of characters in string ignored</param> /// <returns>byte array, in the same left-to-right order as the hexString</returns> public static byte[] GetBytes(string hexString, out int discarded) { discarded = 0; // XML Reader/Writer is highly optimized for BinHex conversions // use instead of byte/character replacement for performance on // arrays larger than a few dozen elements hexString = "<node>" + hexString + "</node>"; System.Xml.XmlTextReader tr = new System.Xml.XmlTextReader( hexString, System.Xml.XmlNodeType.Element, null); tr.Read(); System.IO.MemoryStream ms = new System.IO.MemoryStream(); int bufLen = 1024; int cap = 0; byte[] buf = new byte[bufLen]; do { cap = tr.ReadBinHex(buf, 0, bufLen); ms.Write(buf, 0, cap); } while (cap == bufLen); return ms.ToArray(); }