列出<byte>并复制字节数组?</byte>

时间:2012-03-24 01:11:11

标签: c# .net list copy byte

所以我正在使用文件格式。文件格式包含数据块...所以我所拥有的是“块”列表的数组。当我通过函数向类添加数据时,会添加这些内容。

现在,当我保存文件时,我需要在开头“插入”一个块。现在我知道这可能没有意义,但我需要在计算块中数据类型的数据偏移量之前添加该块(这是空白的)。如果不这样做,数据偏移会被搞砸。插入空白块之后,我创建一个新的byte []数组,在其中复制必要的数据,然后“覆盖”我用更新的字节数组插入的空白块。

我需要这样做的主要原因是因为我插入的datachunk包含其他数据的偏移量,因此我需要在添加完所有内容后创建偏移量。

基本上我拥有的是(仅简化):

    public struct SizeIndexPair {
        public int Size;
        public int Index;
    };

    public class Chunks {
        private Dictionary<int, SizeIndexPair> reserved;
        public List<List<byte> > DataChunks;

        ...

        public void Reserve(int ID, int size, int index) {
            SizeIndexPair sip;
            sip.Size = size;
            sip.Index = index;
            reserved.Add(ID, sip);
            List<byte> placeHolder = new List<byte>(size);
            DataChunks.Insert(index, placeHolder);
        }

        public void Register(int ID, byte[] data) {
            SizeIndexPair sip = reserved[ID];
            if (sip.Size != data.Length) 
                throw new IndexOutOfRangeException();
            for (int i = 0; i < data.Length; i++) {
                DataChunks[sip.Index][i] = data[i];
            }
        }
    };

(我在这里使用List(of byte)因为我可能需要向现有块添加额外数据)

我希望我有意义。

这种方法的问题在于我正在“加倍”数组,这会占用更多内存。此外,复制数据的过程可能会使我的应用程序变慢,特别是因为该文件通常包含大量数据。

有更好的方法吗?

一件容易解决的问题是修复List,而不是保留/注册数组,我可以直接通过指针访问数组。有没有办法做到这一点?

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

如果目标是在List<List<byte>>中的其他条目之前插入特定的字节集合,那么您可以使用重载:

DataChunks.Insert(0, prefix);

其中0表示要插入的集合中元素的索引,prefix是要插入的值。

然后得到结果字节流:

foreach(byte b in DataChunks.SelectMany(c => c))
    Console.WriteLine(b); // replace with the method you use to write the `List of Lists of Bytes

答案 1 :(得分:0)

你应该查看名为“CopyTo”的字节数组函数

例如,这是几年前我写的网络数据包处理程序中的一些旧代码:

Public Sub SendData(ByVal Data() As Byte)
    Try
        Dim Length As Integer = Data.Length
        Dim D() As Byte = BitConverter.GetBytes(Data.Length)
        ReDim Preserve D(D.Length + Data.Length - 1)
        Data.CopyTo(D, 4)
        client.BeginSend(D, 0, D.Length, 0, AddressOf sockSendEnd, client)
    Catch
        RaiseEvent onError(Err.Description)
    End Try
End Sub