简体   繁体   English

使用C#将现有串行端口读取为字节

[英]ReadExisting serial port to bytes using C#

I am trying to use ReadExisting method under the serial port. 我正在尝试在串行端口下使用ReadExisting方法。 the method return for me a string. 该方法为我返回了一个字符串。 however I want to convert this data into bytes. 但是我想将此数据转换为字节。

the sender sends me bytes witout encoding. 发送者向我发送未编码的字节。 however when I am trying to use the ReadExisting method and convert it to bytes I am not getting the exact bytes. 但是,当我尝试使用ReadExisting方法并将其转换为字节时,我没有得到确切的字节。 (closer but no all of them are translate it correctly. (更接近,但并非所有人都能正确翻译。

I tried to use get bytes in Encoding (tried UTF8,ASCII and others) however didn't find the correct one. 我尝试在编码中使用get字节(尝试过UTF8,ASCII和其他),但未找到正确的字节。 how can I know which encoding it does? 我怎么知道它是哪种编码?

 private void _serialPort_DataReceived(object sender, 
 SerialDataReceivedEventArgs e)
    {
        int BytesToRead = _serialPort.BytesToRead;
        if (BytesToRead > 1)
        {

            string tmpExist = _serialPort.ReadExisting();
            SerialInfo _SerialInfo = new SerialInfo();

            byte[] tmpData = Encoding.ASCII.GetBytes(tmpExist); // 
 System.Text.Encoding.ASCII.GetBytes(tmpExist);
 }

Thanks 谢谢

I believe the serial port .Encoding property will get you what you are after. 我相信串行端口.Encoding属性将为您提供所需的服务。 It has been a few years, but I think that was it. 已经有几年了,但是我认为就是这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM