0

How can I search within an array of byte for a specific byte?

For example, I use Instr(String, "something to search") or InstrRev(String, "something to search") for strings. I basically don't want to loop through the byte array, because I have extremely long byte arrays and I want to search bytes in a flash.

I just need the fastest and the simplest code possible for my task.

What would be a faster quicker and simpler way to search? A byte array of a file, or to stream a file with filestream and then to search within it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Afnan Makhdoom
  • 654
  • 1
  • 8
  • 20

2 Answers2

2

The System.Array class exposes many useful methods when working with arrays.

Dim [array] As Byte() = New Byte() {1, 2, 4, 6, 3}
Dim find As Byte = 3
Dim index As Integer = System.Array.IndexOf(Of Byte)([array], find)

If (index = -1) Then
    'Not found...
Else
    'Found!
End If
Bjørn-Roger Kringsjå
  • 9,849
  • 6
  • 36
  • 64
  • Can you please tell me how can I find the index of 2 or more consecutive byte patterns? The same way? – Afnan Makhdoom Dec 25 '13 at 16:16
  • @AfnanMakhdoom Take a look at this post, [byte() array pattern search](http://stackoverflow.com/questions/283456/byte-array-pattern-search). Convert the code at [developerfusion](http://www.developerfusion.com/tools/convert/csharp-to-vb/). – Bjørn-Roger Kringsjå Dec 25 '13 at 16:19
  • how can I search multiple points of one array in another array, for example array1(2) + array1(3) + array1(4) in another array say array2? – Afnan Makhdoom Aug 03 '14 at 02:27
0

Use:

Dim Tag As Byte, cTag() As Byte = UTF8Encoding.UTF8.GetBytes("Host: ")  ' For poc
Dim Ret As Byte, cTagLength as Byte = cTag.Length 'POS

For Each Ret In cBuffer 'Ret pos seek "Host: "
    If cBuffer(Ret) = cTag(Tag) Then
        Tag = +1 ' Avryleter
    Else
        Tag = 0 ' Reset
    End If
    If Tag = cTagLength Then 
        Exit For
    End If
Next

It still the same code (in VB.NET).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131