检查两个字节数组的相等性 [英] Checking equality for two byte arrays

查看:49
本文介绍了检查两个字节数组的相等性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检查两个字节数组的相等性,并且我需要一些帮助,因为即使数组应该相等,我所返回的内容仍为false.

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.

在调试中,我可以看到a1和b1都相等,但是并没有进入while循环以增加i.

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

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

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

推荐答案

您需要在某处添加返回值.这应该起作用:

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

但这要简单得多:

return a1.SequenceEqual(b1);

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

Alternatively, you could use IStructuralEquatable from .NET 4:

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


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


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

下载此LINQPad文件即可自行运行基准测试.

Download this LINQPad file to run the benchmark yourself.

这篇关于检查两个字节数组的相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆