c# - 计算二进制文件中字节模式的出现次数

标签 c# hex

我希望我的程序读取二进制文件的十六进制值并计算“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

最佳答案

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

这里我做了两个实现:

        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 次。

关于c# - 计算二进制文件中字节模式的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54060174/

相关文章:

c# - 确定 XDocument 中的元素

c# - 将 dapper 与 .net 核心一起使用时,对象必须实现 IConvertible 异常

c# - 从整数转换为十六进制

c - 为什么我的二进制数无法正确转换为十六进制?

c++ - 学校作业的简单密码加密

c# - 鼠标位置如何转换为滚动控件?

c# - 类似 magic draw 的工具,但用于生成 C# 代码

c# - 在 Azure 服务器和 UWP 客户端上实现 WebSocket

hex - 为什么PE文件中的MZ DOS Header Signature是0x54AD?

c - 在一个字节中存储 4 个不同的值