2013-08-29 135 views
0

所以,我试图通过C#中的串口对象与设备进行通信。设备正在查找作为命令字符串的一部分发送给它的掩码值。例如,其中一个字符串类似于“SETMASK:{}”,其中{}是无符号的8位掩码。用串口发送非ASCII字符的字符串c#

当我使用终端(如BRAY)与设备通信时,我可以使设备工作。例如,在BRAY终端中,字符串SETMASK:$ FF将把掩码设置为0xFF。然而,我不能为我的生活弄清楚如何在C#中做到这一点。

我已经尝试了以下功能,其中的数据是屏蔽值和CMD是周围的字符串(“SETMASK:”在这种情况下“)。我要去哪里错了

public static string EmbedDataInString(string Cmd, byte Data) 
    { 
     byte[] ConvertedToByteArray = new byte[(Cmd.Length * sizeof(char)) + 2]; 
     System.Buffer.BlockCopy(Cmd.ToCharArray(), 0, ConvertedToByteArray, 0, ConvertedToByteArray.Length - 2); 

     ConvertedToByteArray[ConvertedToByteArray.Length - 2] = Data; 

     /*Add on null terminator*/ 
     ConvertedToByteArray[ConvertedToByteArray.Length - 1] = (byte)0x00; 

     Cmd = System.Text.Encoding.Unicode.GetString(ConvertedToByteArray); 

     return Cmd; 
    } 
+0

当你通过布雷做到这一点,你真的发送三个字符'$','F'和'F'? – hatchet

+0

不,在布雷,这就是你发送非打印字符的方式。 $ XX => 0xXX。所以,$ FF => 0xFF => 0b11111111 – pYr0

回答

0

能?不能确定,但​​我敢打赌你的设备需要1字节的字符,但C#字符是2个字节,尝试使用Encoding.ASCII.GetBytes()将字符串转换为字节数组。返回字节[]数组而不是字符串,因为您最终会将其转换回2字节字符。

using System.Text; 

// ... 

public static byte[] EmbedDataInString(string Cmd, byte Data) 
{ 
    byte[] ConvertedToByteArray = new byte[Cmd.Length + 2]; 
    System.Buffer.BlockCopy(Encoding.ASCII.GetBytes(Cmd), 0, ConvertedToByteArray, 0, ConvertedToByteArray.Length - 2); 

    ConvertedToByteArray[ConvertedToByteArray.Length - 2] = Data; 

    /*Add on null terminator*/ 
    ConvertedToByteArray[ConvertedToByteArray.Length - 1] = (byte)0x00; 

    return ConvertedToByteArray; 
} 

如果您的设备接受其他字符编码,请将ASCII换为适当的ASCII码。

+0

比我的解决方案更简洁一点。很高兴知道。谢谢! – pYr0

0

问题解决了,System.Buffer.BlockCopy()命令在字符串中的每个字符之后嵌入了零。这个作品:

public static byte[] EmbedDataInString(string Cmd, byte Data) 
    { 
     byte[] ConvertedToByteArray = new byte[(Cmd.Length * sizeof(byte)) + 3]; 
     char[] Buffer = Cmd.ToCharArray(); 

     for (int i = 0; i < Buffer.Length; i++) 
     { 
      ConvertedToByteArray[i] = (byte)Buffer[i]; 
     } 

     ConvertedToByteArray[ConvertedToByteArray.Length - 3] = Data; 
     ConvertedToByteArray[ConvertedToByteArray.Length - 2] = (byte)0x0A; 
     /*Add on null terminator*/ 
     ConvertedToByteArray[ConvertedToByteArray.Length - 1] = (byte)0x00; 

     return ConvertedToByteArray; 
    }