【问题标题】:Send string with non-ascii characters out serial port c#从串口c#发送带有非ascii字符的字符串
【发布时间】:2013-08-29 18:01:16
【问题描述】:

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

当我使用终端(如 BRAY)与设备通信时,我可以让设备工作。例如,在 BRAY 终端中,字符串 SETMASK:$FF 会将掩码设置为 0xFF。但是,我一生都无法弄清楚如何在 C# 中做到这一点。

我已经尝试过以下函数,其中 Data 是掩码值,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;
    }

【问题讨论】:

  • 当您通过 Bray 执行此操作时,您实际上发送了三个字符“$”、“F”和“F”?
  • 不,在 Bray 中,这就是发送不可打印字符的方式。 $XX => 0xXX。所以,$FF => 0xFF => 0b11111111

标签: c# serial-port ftdi


【解决方案1】:

不能确定,但​​我敢打赌您的设备需要 1 字节字符,但 C# 字符是 2 字节。尝试使用 Encoding.ASCII.GetBytes() 将字符串转换为字节数组。您可能还需要返回 byte[] 数组而不是字符串,因为您最终会将其转换回 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 换成适当的编码。

【讨论】:

  • 比我的解决方案更简洁一些。很高兴知道。谢谢!
【解决方案2】:

问题已解决,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;
    }

【讨论】:

    猜你喜欢
    • 2020-11-12
    • 2012-04-28
    • 2012-08-16
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多