Reputation: 119
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
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