Android Question B4X Compare two byte arrays

hatzisn

Expert
Licensed User
Longtime User
Is there a direct way to compare two byte arrays other than looping in their incredients?

I send two bytes from the computer and in the Mobile Part I am receiving them correctly
but if I check the following

B4X:
'Obviously comparing objects
If Buffer = "Ok".GetBytes("UTF8") Then

End if

it always returns false although I send "Ok".GetBytes("UTF8") .
 
Last edited:

stevel05

Expert
Licensed User
Longtime User
B4X:
If Buffer = "Ok".GetBytes("UTF8")

Comparing for equality like that will test if it the same byte array, not it's contents. You could use the ByteConverter library

B4X:
 Dim B() As Byte = "OK".GetBytes("UTF8")
    Dim BC As ByteConverter
    Log(BC.StringFromBytes(B,"UTF8") = "OK")

Or java.util.Array class via Javaobject: :

B4X:
    Dim B() As Byte = "OK".GetBytes("UTF8")
    Dim Jo As JavaObject
    Jo.InitializeStatic("java.util.Arrays")
    Log(Jo.RunMethod("equals",Array(B,"OK".GetBytes("UTF8"))))
 
Last edited:
Upvote 0

hatzisn

Expert
Licensed User
Longtime User
Here is a workaround I came with because I want to use it also in B4i. The string comparison I think that would also work but I couldn't risk loosing non printable characters (in case something like that would happen). Here is the solution :

Compare Two Byte Arrays:
Private Sub CompareByteArrays(b1() As Byte, b2() As Byte) As Boolean
    If b1.Length <> b2.Length Then Return False
    Dim ii As Long
    For ii = 0 To b1.Length - 1
        If b1(ii) <> b2(ii) Then
            Return False
        End If
    Next
    Return True
End Sub
 
Upvote 0
Top