C# Replace bytes in Byte[]

后端 未结 6 916
日久生厌
日久生厌 2020-12-06 14:01

What is the best way to replace some bytes in a byte array??

For instance i have bytesFromServer = listener.Receive(ref groupEP); and i can do Bit

6条回答
  •  臣服心动
    2020-12-06 14:29

    Improving on rene's code, I created a while loop for it to replace all occurences:

    public static byte[] ReplaceBytes(byte[] src, byte[] search, byte[] repl)
    {
        byte[] dst = null;
        byte[] temp = null;
        int index = FindBytes(src, search);
        while (index >= 0)
        {
            if (temp == null)
                temp = src;
            else
                temp = dst;
    
            dst = new byte[temp.Length - search.Length + repl.Length];
    
            // before found array
            Buffer.BlockCopy(temp, 0, dst, 0, index);
            // repl copy
            Buffer.BlockCopy(repl, 0, dst, index, repl.Length);
            // rest of src array
            Buffer.BlockCopy(
                temp,
                index + search.Length,
                dst,
                index + repl.Length,
                temp.Length - (index + search.Length));
    
    
            index = FindBytes(dst, search);
        }
        return dst;
    }
    

    This method will work, but if the source bytes is too huge, I prefer to have a "windowing" function to process the bytes chunk by chunk. Else it will take a huge amount of memory.

提交回复
热议问题