string 转 byte[]
/// <summary> /// string 转 byte /// </summary> /// <param name="str"></param> /// <returns></returns> byte[] Str_change_byte(string str) { byte[] Data = new byte[str.Length]; int count = 0; string strSource = str.Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", ""); try { for (int i = 0; i < (strSource.Length - strSource.Length % 2) / 2; i++)//取余3运算作用是防止用户输入的字符为奇数个 { Data[count] = Convert.ToByte(strSource.Substring(i * 2, 2), 16); count++; } if (strSource.Length % 2 != 0)//剩下一位单独处理 { Data[count] = Convert.ToByte(strSource.Substring(strSource.Length - 1, 1), 16);//单独处理B(0B) count++; } } catch (Exception) { MessageBox.Show("Error:数据包含非法字符\n", "错误:", MessageBoxButtons.OK, MessageBoxIcon.Error);//出错提示 return null; } byte[] buf = new byte[count]; Array.Copy(Data, 0, buf, 0, count); //复制原始数据 return buf; }