【问题标题】:Count occurrence of byte pattern in binary file计算二进制文件中字节模式的出现次数
【发布时间】:2019-06-01 06:41:35
【问题描述】:

我希望我的程序读取二进制文件的十六进制值并计算出现次数“45”,现在停留在计数字节模式上。

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

【问题讨论】:

  • 你的困难是什么?只是计算数组中出现的次数,或者您也不确定是否要从文件中读取?
  • 如果提供的答案有帮助,礼仪是将其标记为“答案”,并可能对其有用性表示赞同。这可以防止这个问题出现在 SOF 中的“显示未回答的问题”下,并且还可以为帮助您的人提供更多声誉。

标签: c# hex


【解决方案1】:

您可以循环遍历数组中的每个元素,并在每次找到值 45 时进行计数。或者您可以使用 LINQ Count 并获得相同的结果。

这里我做了两个实现:

        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++;
            }
        }

在这两种实现中,数字 45 都重复了 4 次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多