0

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 :)

Albzoq
  • 13
  • 2
  • strings have characters; streams have bytes; strings can be *encoded* to bytes, but there isn't a direct map between the two unless you first define the encoding; it isn't clear what you want to do here - you can *skip* bytes (by reading them but not processing them), but you can't get the "last n" bytes unless you buffer at least n bytes (presumably in a circular buffer) and wait until you get to the end of the stream – Marc Gravell Jun 02 '15 at 11:20
  • 1
    btw: your reading code is not safe; you could have read 1 byte, 0 bytes, anything up to `MessageProt.Length` bytes; you could have received one half of the logical message, with the other half still en-route (split packets, buffers, etc) - basically: this is **not** how you talk to a socket if you want it to work robustly – Marc Gravell Jun 02 '15 at 11:22
  • Unfortunately I came to a point that when I try to read at a second read stream operation, some bytes are confused or not showing correctly. I am trying a diiferent approach which can be seen below: – Albzoq Jun 02 '15 at 14:12

1 Answers1

1

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.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272