Reading necessary bytes

136 Views Asked by At

is it possible to read only last two bytes from a string. For example I receive 41 0C 34 from a stream socket, and I only need 34. In what way I can do this. Here is my code:

   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;
           }

Note: I need only 34 as I need to convert it to a decimal value and than implement it into an equation. thanks :)

1

There are 1 best solutions below

0
On BEST ANSWER

You can't just "not read" bytes from a socket.

So, read the entire string and select the characters you want as explained in Extract only right most n letters from a string:

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

But as Marc points out in the comments, 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? to call Read() until you read the number of bytes you expect.