如何将字符和字符串转换为字节数组?

时间:2015-07-10 17:24:14

标签: c# arrays character-encoding

无法将字符转换为字符串以获取字节而不是使用数组通过串口发送。

   const char STX = '\u0002';
   const char ETX = '\u0003';
   string pull_shelf_104 = ( STX + "01P00104##" + ETX);

   private byte[] WrapString(string pull_shelf_104)
   {
       int length = pull_shelf_104.Length;
       byte[] send104 = new byte[length];
       Array.Copy(System.Text.Encoding.ASCII.GetBytes(pull_shelf_104), 0, send104, 0, length);
       return send104;
   }

   private void linkLabel_HC1_100_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
   {
       if (serialPort1.IsOpen)
       {
           byte data = WrapString(string pull_shelf_104);
           serialPort1.Write(data,0,1);
       }
   }

1 个答案:

答案 0 :(得分:3)

您可以尝试简单地说:

private byte[] WrapString(string pull_shelf_104)
{
   return System.Text.Encoding.ASCII.GetBytes(pull_shelf_104);
}