c#用memcmp比较字节数组


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

【c#用memcmp比较字节数组】///
/// 用memcmp比较字节数组
///
/// 字节数组1
/// 字节数组2
/// 如果两个数组相同,返回0;如果数组1小于数组2,返回小于0的值;如果数组1大于数组2,返回大于0的值。
public static int MemoryCompare(byte[] b1, byte[] b2)
{
IntPtr retval = memcmp(b1, b2, new IntPtr(b1.Length));
return retval.ToInt32();
}

///
/// 比较字节数组
///
/// 字节数组1
/// 字节数组2
/// 如果两个数组相同,返回0;如果数组1小于数组2,返回小于0的值;如果数组1大于数组2,返回大于0的值。
public static int MemoryCompare2(byte[] b1, byte[] b2)
{
int result = 0;
if (b1.Length != b2.Length)
result = b1.Length - b2.Length;
else
{
for (int i = 0; i < b1.Length; i++)
{
if (b1[i] != b2[i])
{
result = (int)(b1[i] - b2[i]);
break;
}
}
}
return result;
}

///
/// memcmp API
///
/// 字节数组1
/// 字节数组2
/// 如果两个数组相同,返回0;如果数组1小于数组2,返回小于0的值;如果数组1大于数组2,返回大于0的值。
[DllImport("msvcrt.dll")]
private static extern IntPtr memcmp(byte[] b1, byte[] b2, IntPtr count);
}

    推荐阅读