1

I have a need to serialize the following type

public class MspMessage {
    [DataMember(Order = 1), ProtoMember(1)]
    public byte[] Prefix { get; private set; }
    [DataMember(Order = 2), ProtoMember(2)]
    public MspMessageType MessageType { get; private set; }
    [DataMember(Order = 3), ProtoMember(3)]
    public int DataLength { get; private set; }
    [DataMember(Order = 4), ProtoMember(4)]
    public MspCodes MspCode { get; private set; }
    [DataMember(Order = 5), ProtoMember(5)]
    public byte[] Data { get; private set; }
    [DataMember(Order = 6), ProtoMember(6)]
    public byte Checksum
    {
        get; private set;
    }

    public MspMessage(MspMessageType messageType, MspCodes mspCode, byte[] data) {
        Prefix = new byte[] { 36, 77 };
        MessageType = messageType;
        MspCode = mspCode;
        Data = data;
        DataLength = data?.Length ?? 0;

        if (data == null || data.Length == 0) {
            Checksum = (byte)(0 ^ (int)MspCode);
        } else {
            var checksum = data.Length ^ (int)MspCode;

            checksum = data.Aggregate(checksum, (current, t) => current ^ t);

            Checksum = (byte)checksum;
        }
    }
}

Into a simple binary array like this: {36, 77, 60, 0, 1, 1}. I hacked around with BinaryFormatter and protobuf-net, but both produce added output besides the pure contents of the type. What is the most efficient way to go about this? It's my intention to create derived types that will have additional fields. Thanks!

davidbitton
  • 818
  • 10
  • 20
  • 1
    There is certainly information about the type being serialized. – aybe Aug 28 '16 at 17:49
  • 1
    When you need that much control it is best to add a `byte[] ToByteArray()` and a `static MspMessage FromByteArray(byte[] array)` and just use some BinaryReader and BinaryWriter inside of them – Scott Chamberlain Aug 28 '16 at 17:58
  • Try using Microsofts bond serealization framework , it has a compact binary serializer which seems to have better perf that the ones you tried . – loneshark99 Aug 28 '16 at 20:26

1 Answers1

0

I wound up writing my own IFormatter which essentially is the same thing as a ToByteArray() and FromByteArray(). Thanks!

davidbitton
  • 818
  • 10
  • 20