1

嗨,我的结构如下

    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 转换为单字节数组 []?

4

3 回答 3

0

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

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

于 2013-01-08T02:28:46.413 回答
0

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

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;
    }
}
于 2013-01-08T02:43:04.353 回答
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

于 2013-01-08T02:44:58.970 回答