Comparing byte arrays in C#
2007-08Aug-20
Unless I've been missing something in the past there's no native way in C# to compare byte arrays. Well, you could compare their hashes. But that only tells you if they are different. To make sure they are equal, you need to compare them byte by byte. Hence, using hashes is not only slow, it's also pointless.
public static Int32 Compare(
Byte[] left, Byte[] right, Boolean exact)
{
// The default value is returned when both arrays
// are identical up to the length of the shorter one.
Int32 defaultValue;
Int32 Length;
if (left.Length < right.Length)
{
defaultValue = -1;
Length = left.Length;
}
else if (left.Length > right.Length)
{
if (exact)
defaultValue = 1;
else
defaultValue = 0;
Length = right.Length;
}
else
{
defaultValue = 0;
Length = right.Length;
}
// Compare all bytes up to the length of the shorter array
for( Int32 i=0; i{
if( left[i] < right[i])
return -1;
else if(left[i] > right[i])
return 1;
}
return defaultValue;
}