检查两个字节数组的相等性

时间:2013-08-27 18:27:03

标签: c#

我正在检查两个字节数组的相等性,我想要一些帮助,因为即使数组应该相等,我所返回的也是假的。

在我的调试中,我可以看到a1和b1都相等,但它不会进入while循环内来增加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;
}

这总是返回false:(a1[i]==b1[i])

5 个答案:

答案 0 :(得分:36)

您需要在某处添加返回值。这应该有效:

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;
}

但这更简单:

return a1.SequenceEqual(b1);

或者,您可以使用.NET 4中的IStructuralEquatable

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

如果需要考虑性能,我建议您重写代码以使用Binary类,该类专门针对此类用例进行了优化:

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

我的机器上的快速基准测试给出了以下统计数据:

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

下载this LINQPad file以自行运行基准测试。

答案 1 :(得分:35)

要检查相等性,您可以写:

var areEqual =  a1.SequenceEqual(b1);

答案 2 :(得分:5)

我建议使用一些短路来使事情变得更简单,并且当数组是相同的引用(object.ReferenceEquals)时使用a1 = b1来短路:

public bool Equality(byte[] a1, byte[] b1)
{
    // If not same length, done
    if (a1.Length != b1.Length)
    {
        return false;
    }

    // If they are the same object, done
    if (object.ReferenceEquals(a1,b1))
    {
        return true;
    }

    // Loop all values and compare
    for (int i = 0; i < a1.Length; i++)
    {
        if (a1[i] != b1[i])
        {
            return false;
        }
    }

    // If we got here, equal
    return true;
}

答案 3 :(得分:1)

这应该有效:

public bool Equality(byte[] a1, byte[] b1)
{
   if(a1 == null || b1 == null)
       return false;
   int length = a1.Length;
   if(b1.Length != length)
      return false;
   while(length >0) {
       length--;
       if(a1[length] != b1[length])
          return false;           
   }
   return true;        
}

答案 4 :(得分:0)

你应该添加一些return语句:

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

或者,更好的

public bool Equality(byte[] a1, byte[] b1)
{
    if(a1.Length != b1.Length)
    {
        return false;
    }

    for (int i = 0; i < a1.Length; i++)
    {
        if (a1[i] != b1[i])
        {
            return false;
        }
    }
    return true;
}