Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking equality for two byte arrays

Tags:

c#

I am checking the equality of two byte arrays, and I wanted some help because what I have returns false even though the arrays should be equal.

Within my debug I could see both of a1 and b1 are equal, but it is not going inside the while loop to increment i.

public bool Equality(byte[] a1, byte[] b1) {     int i;     bool bEqual;     if (a1.Length == b1.Length)     {         i = 0;         while ((i < a1.Length) && (a1[i]==b1[i]))         {             i++;         }          if (i == a1.Length)         {             bEqual = true;         }     }     return bEqual; } 

This always returns false: (a1[i]==b1[i]).

like image 810
Masriyah Avatar asked Aug 27 '13 18:08

Masriyah


People also ask

How do you know if two byte arrays are equal?

equals(byte[] a, byte[] a2) method returns true if the two specified arrays of bytes are equal to one another. Two arrays are equal if they contain the same elements in the same order.

How to compare two byte arrays?

To compare two-byte arrays, Java has a built-in method Arrays. equal(). It checks for the equality of two arrays.

What is byte and byte array in Python?

python3's bytes and bytearray classes both hold arrays of bytes, where each byte can take on a value between 0 and 255. The primary difference is that a bytes object is immutable, meaning that once created, you cannot modify its elements. By contrast, a bytearray object allows you to modify its elements.


1 Answers

You need to add a return value somewhere. This should work:

public bool Equality(byte[] a1, byte[] b1) {    int i;    if (a1.Length == b1.Length)    {       i = 0;       while (i < a1.Length && (a1[i]==b1[i])) //Earlier it was a1[i]!=b1[i]       {           i++;       }       if (i == a1.Length)       {           return true;       }    }     return false; } 

But this is much simpler:

return a1.SequenceEqual(b1); 

Alternatively, you could use IStructuralEquatable from .NET 4:

return ((IStructuralEquatable)a1).Equals(b1, StructuralComparisons.StructuralEqualityComparer) 

If performance is a concern, I'd recommend rewriting your code to use the Binary class, which is specifically optimized for this kind of use case:

public bool Equality(Binary a1, Binary b1) {     return a1.Equals(b1); } 

A quick benchmark on my machine gives the following stats:

Method                   Min         Max         Avg binary equal:          0.868       3.076       0.933    (best) for loop:              2.636      10.004       3.065 sequence equal:        8.940      30.124      10.258 structure equal:     155.644     381.052     170.693 

Download this LINQPad file to run the benchmark yourself.

like image 64
p.s.w.g Avatar answered Oct 11 '22 16:10

p.s.w.g