字节字段的结构整理到byte []

时间:2013-01-08 02:21:46

标签: c# struct bytearray

您好我的结构如下

    private struct MessageFormat
    {
        public byte[] Header; //start of message
        public byte Fragmentation; //single packet or not
        public byte Encryption; //encrypted message
        public byte[] Authentication; //password
        public byte[] Flag; //to locate end of auth
        public byte[] Data; //info
        public byte[] Trailer; //end of message
    }

在填充所有字段后,有一种方便的方法将整个MessageFormat转换为单字节数组吗?

3 个答案:

答案 0 :(得分:0)

每个字节数组实际上存储了对字节数组的引用,因此它不是直接的单个数组。

您需要使用此数据构建单个阵列。我个人会创建方法来执行此操作,创建适当长度的结果byte[],然后使用Array.Copy复制到结果数组中。

答案 1 :(得分:0)

我写了一个示例代码,它会完全按照您的要求进行操作。它结合了Reflection和Buffer.BlockCopy,但它可以提高性能(即预先装箱format,避免匿名类型 - 以及它们在示例中的笨拙,冗余初始化 - 甚至不使用Reflection at全部和硬编码序列化方法)。请注意,我提供的方法不会为结果使用缓冲区,而是在分配数组之前计算最终长度。

var format = new MessageFormat
{
    //Initialize your format
};
//Gets every instance public field in the type
//Expects it to be either byte, either byte[]
//Extracts value, length and type
var fields = typeof (MessageFormat).GetFields().
    Select(f => f.GetValue(format)).
    Select(v => new
    {
        Value = v,
        Type = v is byte ? typeof (byte) : typeof (byte[]),
        Length = v is byte ? 1 : (v as byte[]).Length
    }).
    ToArray();
//Calculates the resulting array's length
var totalLength = fields.Sum(v => v.Length);
var bytes = new byte[totalLength];
var writingIndex = 0;
foreach (var field in fields)
{
    //If the field is a byte, write at current index,
    //then increment the index
    if (field.Type == typeof (byte))
        bytes[writingIndex++] = (byte) field.Value;
    else
    {
        //Otherwise, use a performant memory copy method
        var source = field.Value as byte[];
        var sourceLength = source.Length;
        Buffer.BlockCopy(source, 0, bytes, writingIndex, sourceLength);
        writingIndex += sourceLength;
    }
}

答案 2 :(得分:0)

有许多方法可以做到这一点,但所有这些方法都需要逐字段地提取字节。

这是一个:

var msg = new MessageFormat();
var arr = new byte[msg.Header.Length + 1 + 1 + msg.Authentication.Length + msg.Flag.Length + msg.Data.Length + msg.Trailer.Length];
using (var stream = new MemoryStream(arr, 0, arr.Length, true))
{
    stream.Write(msg.Header, 0, msg.Header.Length);
    stream.WriteByte(msg.Fragmentation);
    stream.WriteByte(msg.Encryption);
    stream.Write(msg.Authentication, 0, msg.Authentication.Length);
    stream.Write(msg.Flag, 0, msg.Flag.Length);
    stream.Write(msg.Data, 0, msg.Data.Length);
    stream.Write(msg.Trailer, 0, msg.Trailer.Length);
}

您还可以使用Buffer.BlockCopyArray.Copy