Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two byte arrays in .NET

How can I do this fast?

Sure I can do this:

static bool ByteArrayCompare(byte[] a1, byte[] a2) {     if (a1.Length != a2.Length)         return false;      for (int i=0; i<a1.Length; i++)         if (a1[i]!=a2[i])             return false;      return true; } 

But I'm looking for either a BCL function or some highly optimized proven way to do this.

java.util.Arrays.equals((sbyte[])(Array)a1, (sbyte[])(Array)a2); 

works nicely, but it doesn't look like that would work for x64.

Note my super-fast answer here.

like image 980
Hafthor Avatar asked Sep 04 '08 07:09

Hafthor


People also ask

How do you compare two bytes?

Byte compare() method in Java with examplesThe compare() method of Byte class is a built in method in Java which is used to compare two byte values. Parameters: It takes two byte value 'a' and 'b' as input in the parameters which are to be compared. Return Value: It returns an int value.

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.

Can you compare arrays in C#?

How to compare two arrays in c# using SequenceEqual method. We can also compare two arrays for their equality using ASequenceEqual method. The method takes two arguments arr1 and arr2. By comparing both the array it will return a Boolean value true or false if they are equal or not respectively.

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.


2 Answers

You can use Enumerable.SequenceEqual method.

using System; using System.Linq; ... var a1 = new int[] { 1, 2, 3}; var a2 = new int[] { 1, 2, 3}; var a3 = new int[] { 1, 2, 4}; var x = a1.SequenceEqual(a2); // true var y = a1.SequenceEqual(a3); // false 

If you can't use .NET 3.5 for some reason, your method is OK.
Compiler\run-time environment will optimize your loop so you don't need to worry about performance.

like image 195
aku Avatar answered Sep 23 '22 15:09

aku


P/Invoke powers activate!

[DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)] static extern int memcmp(byte[] b1, byte[] b2, long count);  static bool ByteArrayCompare(byte[] b1, byte[] b2) {     // Validate buffers are the same length.     // This also ensures that the count does not exceed the length of either buffer.       return b1.Length == b2.Length && memcmp(b1, b2, b1.Length) == 0; } 
like image 31
plinth Avatar answered Sep 24 '22 15:09

plinth