C# 字符串转换成byte数组

快乐鱼儿 1年前 ⋅ 700 阅读
        /// <summary>
        /// 字符串转换成byte数组
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public byte[] convertStringToByte(string content)
        {
            byte[] bResult ;
            int iLength = content.Length;

            try
            {
                if (iLength % 2 == 0)
                {
                    bResult = new byte[iLength / 2];
                    for (int i = 0; i < iLength / 2; i++)
                    {
                        bResult[i] = Convert.ToByte(content.Substring(i * 2, 2), 16);
                    }
                }
                else
                {
                    bResult = new byte[iLength / 2 + 1];
                    for (int i = 0; i < iLength / 2; i++)
                    {
                        bResult[i] = Convert.ToByte(content.Substring(i * 2, 2), 16);
                    }
                    bResult[iLength / 2] = Convert.ToByte(content.Substring(iLength - 1, 1), 16);
                }
                return bResult;
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }

全部评论: 0

    我有话说: