1. 程式人生 > >Byte[] 與String 互轉

Byte[] 與String 互轉

16進位制Byte[]轉String

 public static string ToHexString(byte[] bytes)
        {
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    strB.Append(bytes[i].ToString("X2") + " ");
                }
                hexString = strB.ToString();
            }
            return hexString;
        }

String轉16進位制Byte[]

string[] sourceData = richTextBox1.Text.Trim().Split(' ');
             
                List<byte> data = new List<byte>();
                for (int i = 0; i < sourceData.Length; i++)
                {
                    data.Add(Convert.ToByte(sourceData[i], 16));
                }

return data.ToArray();