|
-
Aug 26th, 2023, 06:46 PM
#1
Binary search for ANSI string
I've already got this working, but very inefficiently.
I need to search for an ANSI string in a Binary file. The file will already be opened as Binary.
Currently, I'm reading in chunks, and then converting those chunks to Unicode, and then using Instr against my search string.
I'd much prefer to convert my "sNeedle" string to a byte array, and do the search without messing with Unicode, but I don't have an algorithm to search for a byte array within a much larger byte array, which is what I need.
I took a look at InstrB, but I've never used that and I'm not sure how it works. I did do the following test, but it didn't do anything useful (always returning 0).
Code:
Option Explicit
Private Sub Form_Load()
Dim bb() As Byte
ReDim bb(3)
bb(0) = 5
Dim bb2() As Byte
ReDim bb2(100)
bb2(44) = 5
Debug.Print InStrB(bb, bb2)
End Sub
Any ideas/suggestions?
---------------
p.s. I suppose I could write loops to do my search, but I'm not sure that'd be any faster than what I'm doing.
---------------
Here, I'll post what I'm doing (but don't like):
Code:
Private Function BinaryFileSearch(hFle As Integer, sSearchString As String, _
Optional iStartPosition As Long = 1&, _
Optional iFoundPosition As Long) As Boolean
' Returns true if sSearchString is found, else false.
' sSearchString can be no longer than 128.
' The lFoundPosition is a return argument.
' It returns the latest position before lStartPosition (if there isn't one after lStartPosition) or
' it returns the earliest position after lStartPosition.
'
Dim sFileData As String
Dim pFile As Long
Dim iLen As Long
Dim iPos As Long
'
sFileData = Space$(1024&)
iLen = LOF(hFle)
pFile = iStartPosition
Do
If pFile > iLen Then Exit Do
Get hFle, pFile, sFileData
iPos = InStr(sFileData, sSearchString)
If iPos <> 0& Then
iFoundPosition = pFile + iPos - 1&
If iFoundPosition >= iStartPosition Then
BinaryFileSearch = True
Exit Do
End If
End If
pFile = ((pFile + 1024&) - Len(sSearchString)) + 1&
Loop
End Function
Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|