Best way to compare two BYTE arrays?

  • Thread starter Thread starter Tom
  • Start date Start date
T

Tom

What's the best way to compare two byte arrays? Right now I am converting
them to base64 strings and comparing those, as so:

'result1 and result2 are two existing byte arrays that have been loaded
Dim data64_1 As String = System.Convert.ToBase64String(result1, 0,
result1.Length)
Dim data64_2 As String = System.Convert.ToBase64String(result2, 0,
result2.Length)
Debug.WriteLine(IIf(data64_1 = data64_2, "Equals", "NOT Equals"))

Seems like there should be an easier way.... but neither IS nor = works, and
there isn't any Compare verb or anything. I could, obviously, loop thru each
one and compare each byte, but that seems like too much effort.

What am I missing?

Tom
 
Tom,
Seems like it's uglier, but it is faster and most ways simpler just to
run a tight "For" loop to compare array element by element, especially if
the array is good sized. If you use it in a lot of places, just write an
""IsEqual(mb1, mb2)" function that returns boolean... something like this...
function IsEqual(ByRef mb1 as byte(), ByRef mb2 as Byte()) as boolean
Dim bRetVal as boolean
Dim index as long

if (mb1.length <> mb2.length) then ' make sure arrays same length
bRetVal = false ' if not quit here... not same
else
for (index = 0 to mb1.length-1) ' run array length looking for
miscompare
if (mb1(index) <> mb2(index)) then
bRetVal = false
exit for
end if
next
end if
return bRetVal
end funtion

then just call the function whereever you need... much leaner than
converting to base64 twice and then compare... especially for larger
arrays...

Hope this helps!!
wardeaux
 
Back
Top