C# Replace bytes in Byte[]

后端 未结 6 911
日久生厌
日久生厌 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:23

    You could program it.... try this for a start... this is however not robust not production like code yet...beaware of off-by-one errors I didn't fully test this...

        public int FindBytes(byte[] src, byte[] find)
        {
            int index = -1;
            int matchIndex = 0;
            // handle the complete source array
            for(int i=0; i=0)
            {
                dst = new byte[src.Length - search.Length + repl.Length];
                // before found array
                Buffer.BlockCopy(src,0,dst,0, index);
                // repl copy
                Buffer.BlockCopy(repl,0,dst,index,repl.Length);
                // rest of src array
                Buffer.BlockCopy(
                    src, 
                    index+search.Length , 
                    dst, 
                    index+repl.Length, 
                    src.Length-(index+search.Length));
            }
            return dst;
        }
    

    Implement as an extension method

    public void Replace(this byte[] src, byte[] search, byte[] repl)
    {
          ReplaceBytes(src, search, repl);
    }
    

    usage normal method:

    ReplaceBytes(bytesfromServer, 
                 new byte[] {0x75, 0x83 } , 
                 new byte[]{ 0x68, 0x65, 0x6c});
    

    Extension method usage:

    bytesfromServer.Replace(
                 new byte[] {0x75, 0x83 }, 
                 new byte[]{ 0x68, 0x65, 0x6c});
    

提交回复
热议问题