簡體   English   中英

清單 <byte> 和復制字節數組?

[英]List<byte> and copying byte arrays?

所以我正在使用文件格式。 該文件格式包含大量數據...因此,我擁有的是用於“塊”的List數組。 當我通過函數將數據添加到類時,這些添加到。

現在,當我保存文件時,我需要在開始時“插入”一個塊。 現在我知道這可能沒有意義,但是我需要在計算塊中數據類型的數據偏移量之前添加該塊(為空白)。 如果我不這樣做,那么數據偏移就會搞砸了。 插入空白塊后,我將創建一個新的byte []數組,在其中復制必要的數據,然后用更新的字節數組“覆蓋”插入的空白塊。

我需要這樣做的主要原因是因為我要插入的數據塊包含其他數據的偏移量,因此我需要在添加所有內容之后創建偏移量。

基本上我有這個(只是簡化):

    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(字節),因為我可能需要向現有塊中添加額外的數據)

我希望我有道理。

這種方法的問題是我正在“加倍”陣列,這正在消耗更多的內存。 再加上復制數據的過程可能會大大降低我的應用程序的速度,尤其是因為該文件通常包含大量數據。

有更好的方法嗎?

可以輕松解決此問題的一件事是修復List,而不是保留/注冊數組,我可以直接通過指針直接訪問數組。 有沒有辦法做到這一點?

謝謝你的幫助。

如果目標是在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

您應該查看名為“ 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM