Hadi
Hadi

Reputation: 119

What is an efficient way to parse fields of data from a serial data stream (C#)?

I have a serial data stream receiving from another device (not stored in a file), the structure of data is like this: Header1 Header2 Length(constant) Data CRC [Footer] Data is made up of various type of fields for example: Data = field1(byte) field2(short) field3(uint) ... fieldN(3-bytes unsigned) I would like to have a structure or class which when I parse data from data stream, I assign its fields with proper data. I need some advice (or good examples) to do it in an optimized way. Thanks in advance.

I used to read all available bytes from serial buffer then search for first occurrence of Header in it, then if CRC matches, assign each variable with its respective bytes in the stream.

Upvotes: 1

Views: 141

Answers (1)

StepUp
StepUp

Reputation: 38199

It is possible to use BinaryReader class to read primitive data types as binary values.

Read more about BinaryReader with code example here

So if you have data like this:

struct SomeSerialData
{
    public byte Header1;
    public UInt16 DataLength;
    public string Data;
    public byte CRC;
}

then you can try to read it like this:

class SomeReader
{
    private BinaryReader _reader;

    public SomeReader(Stream stream)
    {
        _reader = new BinaryReader(stream);
    }

    SomeSerialData ReadSomeSerialData()
    {
        var packet = new SomeSerialData();

        packet.Header1 = _reader.ReadByte();
        packet.DataLength = _reader.ReadUInt16();
        packet.Data = Encoding.ASCII.GetString(
                _reader.ReadBytes(packet.DataLength));
        packet.CRC = _reader.ReadByte();

        return packet;
    }
}

Upvotes: 2

Related Questions