您绝对应该看一下BinarySerializer库,该库生成stream
时不会对数据产生任何额外开销。
下面举个例子,结果如下:
要序列化的类:
public class Packet
{
[FieldOrder(0)]
public byte StartByte = 0x88;
[FieldOrder(1)]
public byte Length { get; set; }
[FieldOrder(2)]
[FieldChecksum(nameof(Checksum), Mode = ChecksumMode.TwosComplement)]
public byte[] Data { get; set; }
[FieldOrder(3)]
public byte Checksum { get; set; }
}
用法:
public void Serialize_UTxxxx_Should_SerializePacketWithDataOnly()
{
var stream = new MemoryStream();
var serializer = new BinarySerializer();
// ASCII 'Hello world!' in hex format
var dataIn = new byte[] { 0x41, 0x61, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21 };
Packet pck = new Packet()
{
Length = Convert.ToByte(dataIn.Length + sizeof(byte) + sizeof(byte) + sizeof(byte)),
Data = dataIn
};
serializer.Serialize(stream, pck);
byte[] dataOut = stream.ToArray();
Debug.WriteLine(Encoding.UTF8.GetString(dataOut));
Thread.Sleep(5000);
}
结果:
注意:这里,校验和仅根据Data
值计算