Testing for a string of zero bytes

  • Thread starter Thread starter simonc
  • Start date Start date
S

simonc

I am reading a series of bytes (around 2000) from a binary file and want the
quickest way to test if all the bytes have a value zero. Would this be by a
string comparison? I'm sure reading the bytes into a byte array and testing
each one individually is NOT the best way. Incidentally I have to repeat this
operation several hundred thousand times so any gain in speed will be
significant.

Grateful for advice.
 
Hi,

If InStr(mystring, "1") Then
MsgBox "contains ones"
Else
MsgBox "all zeroes"
End If

Mike
 
You mean you are looking for a string that consists purely of vbNullChar's ?
I'm sure reading the bytes into a byte array and testing
each one individually is NOT the best way

Think I'd do exactly that, looping a byte array is one of the fastest things
you can do in VBA
This does 2000 * 30 * 2 = 120k loops in a blink

Sub test()
Dim bNotAllZero As Boolean
Dim i As Long, j As Long
Dim s As String
Dim ba() As Byte

s = String(30, vbNullChar)
s = s & "a" ' uncomment for testing

ba = s

For j = 1 To 2000
For i = 0 To UBound(ba)
If ba(i) > 0 Then
bNotAllZero = True
Exit For
End If
Next
Next
MsgBox bNotAllZero & vbCr & _
(j - 1) * (i) & " loops"

End Sub

Regards,
Peter T
 
Maybe a simple string comparison is faster. But it depends what you want to
do overall (eg other checking of the bytes), chances of a non-nullchar near
the beginning, etc. Try both methods with your actual data

Sub test2()
Dim bNotAllZero As Boolean
Dim i As Long, j As Long
Dim s As String, s2 As String
Dim ba() As Byte

s = String(2000, vbNullChar)
s2 = String(Len(s), vbnullcar)

's = s & "a" ' uncomment for testing

For i = 1 To 2000
bNotAllZero = s <> s2
Next

MsgBox bNotAllZero
End Sub

Note I increased the length to 2000 as you say that's what you are dealing
with.

Regards,
Peter T
 
It all depends a bit how you have these bytes.
Are they in a string variable, in an array or are they still in a file?
Post the relevant code.

RBS
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top