C#的字节数组比较 [英] C# byte array comparison

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

问题描述

我在使用.NET 3.0的C#两个字节数组。

I have two byte arrays in C# using .NET 3.0.

什么是最有效的方式来比较两个字节数组是否包含每个元素的相同的内容?

What is the "most efficient" way to compare whether the two byte arrays contains the same content for each element?

例如,字节数组 {为0x1,0X2} 是一样的 {为0x1,0X2} 。但是字节数组 {为0x1,0X2} 和字节数组 {0X2,为0x1} 是不一样的。

For example, byte array {0x1, 0x2} is the same as {0x1, 0x2}. But byte array {0x1, 0x2} and byte array {0x2, 0x1} are not the same.

推荐答案

好了,你可以使用:

public static bool ByteArraysEqual(byte[] b1, byte[] b2)
{
    if (b1 == b2) return true;
    if (b1 == null || b2 == null) return false;
    if (b1.Length != b2.Length) return false;
    for (int i=0; i < b1.Length; i++)
    {
        if (b1[i] != b2[i]) return false;
    }
    return true;
}

(我通常使用大括号的一切,但我想我会尝试这样的布局风格只是为了改变...)

(I normally use braces for everything, but I thought I'd experiment with this layout style just for a change...)

这有几个的优化而 SequenceEqual 不能(或没有)执行 - 如前期长度检查。直接数组访问也将更有效率一点比使用枚举。

This has a few optimisations which SequenceEqual can't (or doesn't) perform - such as the up-front length check. Direct array access will also be a bit more efficient than using the enumerator.

诚然这是不太可能在大多数情况下,显著的差异...

Admittedly it's unlikely to make a significant difference in most cases...

您可以的可能的使其更快的非托管code。通过使其在一个时间比较32或64位,而不是8 - 但我不希望code上飞。

You could possibly make it faster in unmanaged code by making it compare 32 or 64 bits at a time instead of 8 - but I wouldn't like to code that on the fly.

这篇关于C#的字节数组比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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