2013-08-29 130 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; 
    }