读取必要的字节

Reading necessary bytes

是否可以只读取字符串的最后两个字节。例如,我从流式套接字接收到 41 0C 34,而我只需要 34。我可以用什么方式做到这一点。这是我的代码:

   public string ReadSensor(ISensor sensor)
    {

        if (ConnectedPort == null)
            return null;
        if (client.Connected)
        {

            string PIDhex = (sensor.GetValue(this)).ToString("x2"); ;

           string PID = Convert.ToString("01"+PIDhex+"\r");

           byte[] byteAir = System.Text.Encoding.ASCII.GetBytes(Convert.ToString(PID));

           stream.Write(byteAir, 0, byteAir.Length);

           byte[] MessageProt = new byte[8];
           stream.Read(MessageProt,0,MessageProt.Length);
           var str = System.Text.Encoding.ASCII.GetString(MessageProt);

           string output = Convert.ToString(str);
           return output;
           }

注意:我只需要 34,因为我需要将其转换为十进制值,然后将其转化为方程式。谢谢:)

你不能只从套接字中 "not read" 字节。

因此,阅读整个字符串和 select 您想要的字符,如 Extract only right most n letters from a string 中所述:

string lastTwo = input.Substring(input.Length - 2);

但作为 , your reading code won't work properly. It's a coincidence it works now, but it can fail miserably. See What does Filestream.Read return value mean? How to read data in chunks and process it? 调用 Read() 直到您读取到您期望的字节数。