0

I'm pretty new to C# and I have to handle a byte stream that I receive. In C++ I usually used something like that:

 #pragma pack(push, DTA_VLS, 1) 
 typedef    struct  tsHEADER
 {
    WORD                wLength;        
    WORD                wIdCounter;         
    WORD                wxxxx;      
    WORD                wxxxx2;     
 }  tHEADER;
 #pragma pack(pop, DTA_VLS)

and then when I received a byte array I could do something like that:

tHEADER header*;

header = receivedByteArray;
if(header->wLength >0)
{
   do something
}

Is there something similar I could do in C# when I want to read a received telegram or create a new one? Or can I do only something like that:

byte[] Tel= new byte(5);
byte[0]= Length;
byte[1]=ID;
// and so on
computermaus
  • 63
  • 2
  • 8

1 Answers1

0

I think the best thing you can do is use the BinaryWriter and then make a small class to hold the data. You can also use BinaryReader to read the bytes back in. There is a BinaryFormatter, but I am pretty sure that has extra meta data in it though (don't hold me to that).

public class MyPackage
{
    public int Length => 12; // or 16 if Length is included

    public int Id { get; set; }

    public int Number1 { get; set; }

    public int Number2 { get; set; }

    public byte[] SerializeToBinary()
    {
        using (var memoryStream = new MemoryStream())
        using (var writer = new BinaryWriter(memoryStream))
        {

            writer.Write(Length);
            writer.Write(Id);
            writer.Write(Number1);
            writer.Write(Number2);

            return memoryStream.ToArray();
        }
    }

    public void DeserializeFromBinary(byte[] data)
    {
        using(var memoryStream = new MemoryStream(data))
        using(var reader = new BinaryReader(memoryStream))
        {
            var length = reader.ReadInt32();
            if (length != Length)
                throw new Exception("Some error if you care about length");

            Id = reader.ReadInt32();
            Number1 = reader.ReadInt32();
            Number2 = reader.ReadInt32();
        }
    }
}
TyCobb
  • 8,909
  • 1
  • 33
  • 53