Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - byte array - byte[] - Is there a simple comparer? [duplicate]

Have I just forgotten the obvious, or is the "manual" comparer the best way to go?

Basically, I just want to compare the contents of type (small) byte-arrays. If all bytes match, the result should be true, otherwise false.

I was expecting to find that Array.Equals or Buffer.Equals would help.

Demonstration Code:

  var a = new byte[]{1, 2, 3, 4, 5};
  var b = new byte[]{1, 2, 3, 4, 5};
  Console.WriteLine(string.Format("== : {0}", (a == b)));
  Console.WriteLine(string.Format("Equals : {0}", a.Equals(b)));
  Console.WriteLine(string.Format("Buffer.Equals : {0}", Buffer.Equals(a, b)));
  Console.WriteLine(string.Format("Array.Equals = {0}", Array.Equals(a, b)));
  Console.WriteLine(string.Format("Manual_ArrayComparer = {0}", ArrayContentsEquals(a, b)));

Manual function:

/// <summary>Returns true if all elements of both byte-arrays are identical</summary>
public static bool ArrayContentsEquals(byte[] a, byte[] b, int length_to_compare = int.MaxValue)
{
  if (a == null || b == null) return false;
  if (Math.Min(a.Length, length_to_compare) != Math.Min(b.Length, length_to_compare)) return false;
  length_to_compare = Math.Min(a.Length, length_to_compare);
  for (int i = 0; i < length_to_compare; i++) if (a[i] != b[i]) return false;
  return true;
}
like image 679
Steven_W Avatar asked Mar 05 '15 11:03

Steven_W


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C full form?

Full form of C is “COMPILE”.

Why is C named so?

Because a and b and c , so it's name is C. C came out of Ken Thompson's Unix project at AT&T. He originally wrote Unix in assembly language. He wrote a language in assembly called B that ran on Unix, and was a subset of an existing language called BCPL.


1 Answers

You are looking for SequenceEqual method.

a.SequenceEqual(b);

Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.

like image 127
Selman Genç Avatar answered Sep 20 '22 02:09

Selman Genç