计数二进制文件中字节模式的出现

时间:2019-01-06 09:19:58

标签: 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

1 个答案:

答案 0 :(得分:0)

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

在这里,我同时实现了两种实现方式:

Public Class Form1
    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()
        ' Sample data
        DataGridView1.Columns.Add("col1", "col1")
        DataGridView1.Columns.Add("col2", "col2")
        DataGridView1.Columns.Add("col3", "col3")
        DataGridView1.Rows.Add(1, 2, 3)
        DataGridView1.Rows.Add(1, 2, 3)
        DataGridView1.Rows.Add(1, 2, 3)
        DataGridView1.Rows.Add(1, 3, 3)
        DataGridView1.Rows.Add(2, 2, 3)
    End Sub
    Private Function CountDistinctRows() As Integer
        Dim distinctRows As Integer = 0
        Dim alreadyCountedRows = New List(Of DataGridViewRow)
        For Each row As DataGridViewRow In DataGridView1.Rows
            Dim isRowAlreadyCounted As Boolean
            For Each r As DataGridViewRow In alreadyCountedRows
                isRowAlreadyCounted = AreRowsEqual(row, r)
                If isRowAlreadyCounted Then Exit For
            Next
            ' If we have row, which wasn't already counted, we have to add it
            ' to collection of added rows and increment the counter of distinct rows
            If Not isRowAlreadyCounted Then
                alreadyCountedRows.Add(row)
                distinctRows = distinctRows + 1
            End If
        Next
        Return distinctRows
    End Function

    Private Function AreRowsEqual(row1 As DataGridViewRow, row2 As DataGridViewRow)
        ' Sanity check
        If row1.Cells.Count <> row2.Cells.Count Then Throw New ArgumentException("Rows are of different size!")
        For i = 0 To row1.Cells.Count - 1
            If row1.Cells(i).Value <> row2.Cells(i).Value Then Return False
        Next
        Return True
    End Function
End Class

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