首页 > 代码库 > 16进制字符串转换为byte数组

16进制字符串转换为byte数组

/// <summary>        /// 16进制字符转换为byte数组        /// </summary>        /// <param name="hexString">偶数位,由16进制字符[0-9a-fA-F]组成</param>        /// <returns>null为转换失败</returns>        private byte[] HexStringToBytes(string hexString)        {            if (string.IsNullOrEmpty(hexString))                return null;            int hexStringLength = hexString.Length;            if (hexStringLength % 2 != 0)                return null;                       Regex r = new Regex(@"[0-9a-fA-F]");            if (!r.IsMatch(hexString))                return null;            int bufferLength = hexStringLength / 2;            byte[] buffer = new byte[bufferLength];            for (int i = 0; i < bufferLength; i++)            {                buffer[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); //2个16进制字符转换为一个byte            }            return buffer;        }

16进制字符串转换为byte数组