C#字节数组比较 [英] C# byte array comparison
问题描述
我在 C# 中有两个字节数组,使用 .NET 3.0.
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...
您可以可能通过一次比较 32 位或 64 位而不是 8 位来使其在非托管代码中更快 - 但我不想即时编码.
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屋!