neoniles
neoniles

Reputation: 41

Count occurrence of byte pattern in binary file

I want my program to read hex value of a binary file and count the occurrence '45' and now stuck on counting byte pattern.

public static byte[] GetOccurrence(string dump)
{
    using (BinaryReader b = new BinaryReader(new FileStream(dump, FileMode.Open)))
    {
        bufferB = new byte[32];
        b.BaseStream.Seek(0x000000, SeekOrigin.Begin);
        b.Read(bufferB, 0, 32);
        return bufferB;
    }
}  

bufferA = GetOccurrence(textOpen.Text);   // textOpen.Text is the opened file

// bufferA now stores 53 4F 4E 59 20 43 4F 4D 50 55 54 45 52 20 45 4E 54 45 52 54 41 49 4E 4D 45 4E 54 20 49 4E 43 2E

// trying to count occurrence of '45' and display the total occurrence in textbox

Upvotes: 2

Views: 557

Answers (1)

Alex Leo
Alex Leo

Reputation: 2851

You can loop trough each element in the array and count each time the value 45 is found. Or you can use LINQ Count and achieve the same result.

Here I have made both implementations:

        var bufferA = new byte[] { 53, 0x4F, 0x4E, 59, 20, 43, 0x4F, 0x4D, 50, 55, 54, 45, 52, 20, 45, 0x4E, 54, 45, 52, 54, 41, 49, 0x4E, 0x4D, 45, 0x4E, 54, 20, 49, 0x4E, 43, 0x2E };
        //Using LINQ
        var numOfRepetition = bufferA.Count(x=> x== 45);

        //Using a foreach loop
        var count = 0;
        foreach(byte number in bufferA)
        {
            if(number == 45)
            {
                count++;
            }
        }

In both implementations the number 45 is repeated 4 times.

Upvotes: 1

Related Questions