Search code examples
c#replacebyte

C# Replace bytes in Byte[]


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 BitConverter.ToString(bytesFromServer) to convert it into a readable format to return something along the lines of

48 65 6c 6c 6f 20 
74 68 65 72 65 20 
68 65 6c 70 66 75 
6c 20 70 65 6f 70 
6c 65   

I would like to replace something inside of that making "68 65 6c" to something like "68 00 00" (just as an example). There is not .Replace() on a byte[].

Would there be an easy way to convert that back into a byte[]?

Any help appreciated. Thank you!


Solution

  • 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<src.Length; i++)
            {
                if(src[i] == find[matchIndex])
                {
                    if (matchIndex==(find.Length-1))
                    {
                        index = i - matchIndex;
                        break;
                    }
                    matchIndex++;
                }
                else if (src[i] == find[0])
                {
                    matchIndex = 1;
                }
                else
                {
                    matchIndex = 0;
                }
    
            }
            return index;
        }
    
        public byte[] ReplaceBytes(byte[] src, byte[] search, byte[] repl)
        {
            byte[] dst = null;
            int index = FindBytes(src, search);
            if (index>=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});