Split a byte array at a delimiter

前端 未结 6 1995
遥遥无期
遥遥无期 2021-01-02 15:49

I\'m having a bit of an issue and, the other questions here didn\'t help me much.

I am a security student and I am trying to write a crypter for a project. For those

6条回答
  •  抹茶落季
    2021-01-02 16:22

    Here's mine. It only does the split once though. I made no attempt at making it performant.

    public static byte[][] Split(this byte[] composite, byte[] seperator)
    {
        bool found = false;
    
        int i = 0;
        for (; i < composite.Length - seperator.Length; i++)
        {
            var compositeView = new byte[seperator.Length];
            Array.Copy(composite, i, compositeView, 0, seperator.Length);
    
                found = compositeView.SequenceEqual(seperator);
            if (found) break;
        }
    
        if(found == false)
        {
            return null;
        }
    
        var component1Length = i;
        var component1 = new byte[component1Length];
    
        var component2Length = composite.Length - seperator.Length - component1Length;
        var component2 = new byte[component2Length];
        var component2Index = i + seperator.Length;
    
        Array.Copy(composite, 0, component1, 0, component1Length);
        Array.Copy(composite, component2Index, component2, 0, component2Length);
    
        return new byte[][]
        {
            component1,
            component2
        };
    }
    

    tested (partially):

    byte[] b1 = new byte[] { 1, 2, 3, 4, 1, 1, 5 };
    byte[] b2 = new byte[] { 1, 1 };
    var parts1 = b1.Split(b2); // [1,2,3,4],[5]
    
    byte[] b3 = new byte[] { 1, 1, 3, 4, 4, 1, 5 };
    byte[] b4 = new byte[] { 1, 1 };
    var parts2 = b3.Split(b4); // [],[3,4,4,1,5]
    
    byte[] b5 = new byte[] { 0, 0, 3, 4, 4, 1, 1 };
    byte[] b6 = new byte[] { 1, 1 };
    var parts3 = b5.Split(b6); // [0,0,3,4,4],[]
    
    byte[] b7 = new byte[] { 1, 2, 3, 4, 5 };
    byte[] b8 = new byte[] { 1, 2, 3, 4 };
    var parts4 = b7.Split(b8); // [],[5]
    
    byte[] b9 = new byte[] { 1, 2, 3, 4, 5 };
    byte[] b0 = new byte[] { 2, 3, 4, 5 };
    var parts5 = b9.Split(b0); // [1],[]
    
    byte[] c1 = new byte[] { 1, 2, 3, 4, 5 };
    byte[] c2 = new byte[] { 6 };
    var parts6 = c1.Split(c2); // null
    

提交回复
热议问题